Understanding the Zend Framework, Part 1: The basicsBuilding the perfect reader Skill Level: Intermediate John Mertic (
[email protected]) Software Engineer SugarCRM 27 Jun 2006 Updated 18 Jan 2011 It has been four years since this series was first published, and since then, the Zend Framework has grown up to become one of the most popular PHP frameworks. Technical alliances with companies such as Abobe, Microsoft, and IBM, have strengthened the support and stability of the framework, which is now used by startups and Fortune 500 companies around the world. This article gives you a high-level view of the Zend Framework, explaining its general concepts and preparing you for the rest of this "Understanding the Zend Framework" series, which goes into the details by chronicling the creation of a new online RSS/Atom feed reader. You won't do much coding here, but for the rest of the series, you should be familiar with PHP. The Zend Framework A couple of years ago, PHP sat at the top of the powerful-but-easy-to-use scripting languages heap — at least as far as popularity was concerned. It was installed on most UNIX®- and Linux®-based web servers. And if you were a programmer, it was easy to get a hosting account that would let you use it. Ruby had been around for quite some time, but not many people were using it. If you wanted to build a web site using dynamically generated content, but you weren't sure that you needed to go so The basics © Copyright IBM Corporation 2006, 2011. All rights reserved. Trademarks Page 1 of 10 developerWorks® ibm.com/developerWorks far as to use an application server like J2EE, you would very likely use PHP. It was fast, easy to learn, convenient, and you didn't have to learn Perl. And then — suddenly, it seemed — the landscape changed. Frameworks and toolkits specifically designed for easily building web-based applications came out of nowhere, led by the popular Ruby on Rails project. Being object-oriented and based on the Model-View-Controller (MVC) paradigm, these projects presented a way to do what everyone wanted to do: create a web site with virtually no effort. Several other solutions have come out since then, such as Django for Python, Catalyst and Mason for Perl, Spring for Java™, and others, each giving developers who are skilled at working in those languages a very modern and easy-to-use framework for building web applications. And PHP has no shortage of these frameworks, either, with CakePHP, Symphony, and CodeIgniter, along with the Zend Framework, all being actively developed. What makes the Zend Framework one of the premier frameworks used by PHP developers is that it provides clean, stable code, complete with intellectual property rights. PHP is gaining ground in the enterprise space, but if you're a Fortune 500 company, you don't want to take a chance on a module submitted to a repository that may or may not be some other company's intellectual property. What is the Zend Framework, exactly? The Zend Framework: • Is based on PHP • Is object-oriented • Uses the MVC paradigm • Has open source contributors • Has contributors who take responsibility for the fact that their code is not the intellectual property of someone else It also aims to make your programming life easier, not just in general by instituting the MVC pattern, but also for specific things you tend to do all the time, like access databases or output to a PDF file. (OK — you probably don't output to a PDF file all the time. But I'll bet you would if it were easier.) Zend Framework components include: Zend_Controller This module provides the overall control for the application. It translates requests into specific actions and makes sure they get executed. Zend_Db This is based on PHP Data Objects (PDO) and provides access to databases in a generic way. The basics © Copyright IBM Corporation 2006, 2011. All rights reserved. Trademarks Page 2 of 10 ibm.com/developerWorks developerWorks® Zend_Feed This makes it easy to consume RSS and Atom feeds. Zend_Filter This provides string-filtering functions, such as isEmail() and getAlpha(). Zend_InputFilter To Zend_Filter, this is designed to work with arrays such as form inputs. Zend_HttpClient This enables you perform HTTP requests easily. Zend_Json This enables you to easily translate PHP objects into JavaScript Object Notation, and vice-versa. Zend_Log This provides general-purpose logging functionality. Zend_Mail This enables you to send text and multipart MIME email. Zend_Mime This is used by Zend_Mail to help decode MIME messages. Zend_Pdf This enables you to create new PDF documents, and load and edit existing PDF documents. Zend_Search This enables you to perform sophisticated searches on your own text. For example, you can build a search engine that returns results based on relevancy or other factors. Zend_Service Contains several submodules that provide easy access to many popular web service APIs, such as those provided by Amazon, Yahoo, Twitter, and Flicker. Zend_View This handles the view portion of the MVC pattern. Zend_XmlRpc This enables you to easily create an XML-RPC server and client. Now let's take a look at where you're going and what you're going to do. The basics © Copyright IBM Corporation 2006, 2011. All rights reserved. Trademarks Page 3 of 10 developerWorks® ibm.com/developerWorks The project To show all of the ins and outs of the Zend Framework, you need a project that covers a lot of ground. That's fine because my favorite project is still the online feed reader. Why? Because I still haven't found one that actually does what I want. Every time a new technology comes my way, I try to make one that's better than the ones I've used before. So you're going to create a new online RSS/Atom feed-reader service. Does the world really need another online feed reader? Maybe. But I don't care if I'm the only one who uses it. And that's the whole point: The Zend Framework aims to make things simple enough that I can take on projects just because I want to, and not because I've justified it with hundreds of thousands of dollars worth of research. So what should this wonder of news-mastering goodness do? For now, it should enable users to: • Save sets of feeds or subscriptions • Read feeds and individual items • Save individual posts • Search saved entries for particular text • Easily read pages that don't have an RSS feed • Print collections of postings Over the course of this series, I'm going to show you how to do all of that using the Zend Framework. The series will run as follows: Part 1: The basics This article, which explains the project in general and the Zend Framework. Part 2: Adding a database This tutorial shows how to use the Zend_DB module to create and manipulate the central database used to store subscription information, as well as saved entries and other information. Part 3: The feeds Now you add feeds into the equation, enabling the user to create an account, subscribe to particular feeds, and display those feeds. This tutorial uses the Zend_Feed and Zend_Inputfilter modules, the latter used to verify email addresses and to strip HTML tags from feed entries. Part 4: When there is no feed: the Zend_HTTPClient Not all sites have feeds, but it's still useful to track everything in one place. This The basics © Copyright IBM Corporation 2006, 2011. All rights reserved. Trademarks Page 4 of 10 ibm.com/developerWorks developerWorks® article shows how to use the Zend_HTTPClient module to create a proxy to pull data into the feed-reader interface. Part 5: Creating PDF files This tutorial explains how to use the Zend_PDF module to enable the user to create a customized PDF of saved articles, images, and search results. Part 6: Sending email This article explains how to use the Zend_Mail module to alert users to new posts and subscribed feeds, and even to send those posts using HTML email. Part 7: Searching This article explains how to use the Zend_Search module to search existing current and saved blog entries for a particular search term and return ranked results. Part 8: Adding related information and services This tutorial explains how to use the Zend_Service modules to pull in information from other services — specifically, Amazon, Flickr, Twitter and Yahoo! The interface will use Ajax to pull books, photos, and search results related to a current blog entry or from a search term the user clicks. Part 9: Adding Ajax The Zend Framework makes it easy to add Asynchronous JavaScript + XML (Ajax) interactions to your application by automatically translating native PHP objects to and from JavaScript Object Notation (JSON). This article shows how to add this functionality to the feed reader. It also includes a basic description of JSON. Setting up The Zend Framework doesn't require any particular installation, but you need to keep some requirements in mind. The Zend Framework requires PHP V5. It is compatible with V5.2.4 and above, so you can use V5.3, but you don't have to. You must, however, make sure that the library directory, where the framework expects to find all of its files, is included in the include_path. To do that, be sure to set it in the php.ini file, as in: ; Windows: "\path1;\path2" include_path = ".;c:\php\includes;e:\sw\zendframework\library" That's it. The basics © Copyright IBM Corporation 2006, 2011. All rights reserved. Trademarks Page 5 of 10 developerWorks® ibm.com/developerWorks The MVC pattern Many developers are not particularly adept at graphic design, so it's helpful to be able to break out the work involved in designing a web-based application so designers can do what they do well, coders can do what they do well, and DBAs can do what they do well. That is the essence of the MVC pattern, which breaks a project down into three tiers. Defining Model-View-Controller Patterns are, by definition, ways of doing things that have evolved over years because they're a good solution to a problem. The Model-View-Controller (MVC) pattern is no exception. Because of this other organic means of creation, you will occasionally find differences in definitions. For example, some definitions of the MVC pattern define the controller's role as simply to change state, with all of the business logic in the model tier. In the end, the only thing that's important is that the application does what you want it to do most efficiently. The model tier consists of the representation of the actual data. For example, in your feed-reader project, you have users, feeds, and feed entries. Their representation in the database conceptually models their structure and, thus, consists of the model tier. The view tier consists of the logic that actually defines how the displayed data looks. It doesn't decide what the displayed data is — just how it looks. In an ideal world, this template contains no logic. It simply takes the information it's given and displays it. The controller is what actually defines what the data is. The controller, in fact, is where all of the logic resides. In the Zend Framework, this tier controls the actions to be executed. For example, if I want to display a single feed-item object, the responsibility is parsed like this: The feed-item object has a controller, which defines what happens when the display action is called. That action calls back to get the desired data from the model (in other words, the database or other persistent store), then feeds those fields — such as title, content, permalink, and so on — to the view, which simply displays it in the browser. When this article was first written, using an MVC architecture for building a web application was fairly new concept in the web world. But now, with the numerous web frameworks out there built on this principle, MVC has became one of the de-facto standards in web application development. Now let's look at what's expected of you. The basics © Copyright IBM Corporation 2006, 2011. All rights reserved. Trademarks Page 6 of 10 ibm.com/developerWorks developerWorks® Coding guidelines When you are coding for the Zend Framework, or even with the Zend Framework, it is expected that you will follow certain guidelines. These are designed to make group projects easier. In other words, by defining coding conventions, you will not only avoid problems later but you will also make it easier for others to read your code. The Zend Framework documentation includes several pages of guidelines, including: • Make sure the files are clean. In other words, no leading or trailing spaces that can call a web server to unexpectedly send content before headers, standard indents of four spaces, etc. • Start your class name with Zend_ if and only if it is intended to be part of the Zend Framework itself, rather than just an application that uses the framework. • Underscores are forbidden in function names. Use camel-style lowercase (as in getTodaysDate()), instead. • Start your variable names with an underscore only if they are private or protected. • Declare all variables as private, protected, or public. Don't use var. • Use the standard PHP tag, as in <?php ?> — not the short form (<? ?>). • Make sure your code is easy to read. In other words, when you use a period (.) to concatenate text, be sure to put spaces before and after the period to make it more readable. The same holds for adding spaces after commas when declaring an array. • If you must pass-by reference, do it only in the declaration of a function. Call-time pass-by reference is prohibited. • Every PHP file must include documentation that can be read by PhpDocumentor, and the coding guidelines specify certain minimum tags. This is not a complete list of guidelines, of course, but it should give you an idea of the types of requirements. Check the documentation for the full list, so your code more easily fulfills the promise of making PHP projects easier to share. Summary The Zend Framework provides a new IP-certain way to build your PHP applications. In that, it aims to improve your PHP coding experience. In this series, you use the The basics © Copyright IBM Corporation 2006, 2011. All rights reserved. Trademarks Page 7 of 10 developerWorks® ibm.com/developerWorks Zend Framework to build an RSS/Atom feed reader. Future parts of the series will cover data access, searching, web services, and other portions of the framework. In Part 2, you create the login system and start building the database. The basics © Copyright IBM Corporation 2006, 2011. All rights reserved. Trademarks Page 8 of 10 ibm.com/developerWorks developerWorks® Resources Learn • The Zend Framework website maintains the latest documentation. • "Implement SOAP services with the Zend Framework": Check out this article on using SOAP web services with the Zend Framework. • To better understand the goals of the feed-reader project, read "Introduction to Syndication, (RSS) Really Simple Syndication," by Vincent Luria. • Thought Storms ModelViewController explains the MVC and the controversy and confusion surrounding it. • The phpPatterns web site explains MVC from the PHP point of view. • PHP.net is the central resource for PHP developers. • Check out the "Recommended PHP reading list." • Browse all the PHP content on developerWorks. • Follow developerWorks on Twitter. • Expand your PHP skills by checking out IBM developerWorks' PHP project resources. • To listen to interesting interviews and discussions for software developers, check out developerWorks podcasts. • Using a database with PHP? Check out the Zend Core for IBM, a seamless, out-of-the-box, easy-to-install PHP development and production environment that supports IBM DB2 V9. • Stay current with developerWorks' Technical events and webcasts. • Check out upcoming conferences, trade shows, webcasts, and other Events around the world that are of interest to IBM open source developers. • Visit the developerWorks Open source zone for extensive how-to information, tools, and project updates to help you develop with open source technologies and use them with IBM's products, as well as our most popular articles and tutorials. • Watch and learn about IBM and open source technologies and product functions with the no-cost developerWorks On demand demos. Get products and technologies • Download the Zend Framework from Zend Technologies. • Download PHP V5.x from PHP.net. The basics © Copyright IBM Corporation 2006, 2011. All rights reserved. Trademarks Page 9 of 10 developerWorks® ibm.com/developerWorks • Innovate your next open source development project with IBM trial software, available for download or on DVD. • Download IBM product evaluation versions or explore the online trials in the IBM SOA Sandbox and get your hands on application development tools and middleware products from DB2®, Lotus®, Rational®, Tivoli®, and WebSphere®. Discuss • Get involved in the developerWorks community. Connect with other developerWorks users while exploring the developer-driven blogs, forums, groups, and wikis. • Participate in developerWorks blogs and get involved in the developerWorks community. • Participate in the developerWorks PHP Forum: Developing PHP applications with IBM Information Management products (DB2, IDS). About the author John Mertic John Mertic is a software engineer at SugarCRM, and has several years of experience with PHP web applications. At SugarCRM, he has specialized in data integration, mobile and user interface architecture. An avid writer, he has been published in php|architect, IBM Developerworks, and in the Apple Developer Connector, and is the author of the book 'The Definitive Guide to SugarCRM: Better Business Applications'. He has also contributed to many open source projects, most notably the PHP project where is the creator and maintainer of the PHP Windows Installer. The basics © Copyright IBM Corporation 2006, 2011. All rights reserved. Trademarks Page 10 of 10