Home | News | Reports | Articles | Softwares | Websites | Books | Archives  | Sitemap
Linux Daily

LinuxDaily.net
What's new in Zend Framework V1.5

Level: Intermediate

Katie Horn (K4@engineering.phenomenauts.com), Developer, Freelance

15 Apr 2008

The popular open source Zend Framework just got some slick enhancements. Learn what's new in V1.5 and how upgrades, including Zend_Form, Zend_Layout, and Zend_View, enhanced support for GData Web services, and improved Ajax support can help PHP developers easily roll out cutting-edge Web applications.

A software framework is a collection of code libraries designed to take care of all the basics required in an application in a standardized way so application developers can spend their time developing, instead of constantly having to reinvent the wheel. There are dozens of open source PHP development frameworks out there to choose from, and of all those available, the Zend Framework is perhaps the most popular.

Zend stands out by putting a huge emphasis on best practices, which appeals to those of you who value sustainability. Zend also makes a point of constructing the framework in a remarkably modular fashion: Most of the individual Zend Framework components can be pulled completely out and used on their own, which appeals to developers who only need a fraction of the available libraries. Zend's flexibility, combined with the solid standardization that comes with emphasizing best practices, makes it a practical framework for a broad spectrum of purposes.

The already-powerful Zend Framework has gained several entirely new components and component enhancements in V1.5. The upgrades make developing complicated PHP applications even easier and more maintainable down the road due to the implementation of standards in things like form-validation routines and even front-end layout creation. Let's start by taking a look at the Zend_Form component and all it has to offer.

Zend_Form

One of the more exciting additions to the Zend Framework is the Zend_Form component. Web applications are pretty useless without the ability to take input data and act on it, and the easiest way to get data from the user is through a form. Of course, forms can easily turn into the most tedious aspect of developing and maintaining a Web application: You must validate everything that comes in, make sure it's what you thought you were getting, and process every single piece of incoming data individually. All that is assuming you don't have to generate error messages and start the whole thing over, which, of course, you will — quite a daunting task to perform manually, without the ability to reuse code.

The new form component does more than simply allow you to create a form and form elements programmatically. Zend_Form is capable of performing complex validation and displaying error messages on your form when validation fails.

Using Zend_Form is pretty straightforward. First, the form object is instantiated, and its action and method are set. Then, form elements are added to the form object, and form element validators and filters are applied to the individual form elements. The completed form object is rendered and used in the application, and the results are validated and filtered. See Listing 1 for an example of a simple form.


Listing 1. A simple form
                
    require_once 'Zend/Form.php'; 
    $form = new Zend_Form(array( 
        'method'   => 'post', 
        'elements' => array( 
            'name' => array('text', array( 
                'required' => true, 
                'label' => 'Name', 
          'validators' => array('alpha')
            )), 
            'age' => array('text', array( 
                'required' => true, 
                'label' => 'Age', 
          'validators' => array('digits')
            )), 

            'submit' => array('submit', array( 
                'label' => 'Send' 
            )) 
        ), 
    )); 

The results of Listing 1 are shown in Figure 1.


Figure 1. The form
The form

Zend_Form comes with the following elements: button, checkbox, hidden, image, multichckbox, multiselect, password, radio, reset, select, submit, text, and textarea. Zend_Form is not limited to the elements that ship with it: The built-in Zend_Form_Element class allows you to create your own elements.

You can instantiate the form elements manually and attach them to the form or let the form object create and instantiate a new form element of the requested type for you. Every element is individually configurable as required or not, with individual sets of validators and filters that can be attached to their form elements any time prior to the finished form being rendered, before or after the individual elements have been attached to the form object.

There are 19 standard validation types that come ready to use with your form elements. These validators can check for just about every data type you would regularly need to collect — from simple data-type verification to regular-expression matching to e-mail address validation that can be configured to make sure the top-level domain exists, and has an MX record. By default, when a validator returns false, the remaining validation checks are aborted, but that parameter is also configurable for each individual validator.

In Listing 1, an alpha-validator was applied to the name field, and the digit's validator was applied to the age field. When you enter data that fails these validation tests, Figure 2 shows the results of what happens entirely by default.


Figure 2. The form with failed validation tests
The form with failed validation tests

Once the validators are in place, the next step is applying filters. If validators can be said to act like bouncers at a club, filters behave more like personal stylists: Filters take the data in a form element, filter out what you don't want to see on the other side, and pass on what's left. There are 12 standard built-in filter types for doing things like stripping out whitespace, trimming the alpha from the numeric, changing text to uppercase, converting special characters to HTML entities, and stripping disallowed tags. Use a filter when you know the data you want is present in the field, but it badly needs a haircut and a bit of a makeover.

To demonstrate filters in action on our simple form, let's change the elements array.


Listing 2. Applying a filter to the elements array
                
        'elements' => array( 
            'name' => array('text', array( 
                'required' => true, 
                'label' => 'Name', 
          'validators' => array('alpha'),
          'filters' => array('StringToUpper')

            )), 
            'age' => array('text', array( 
                'required' => true, 
                'label' => 'Age', 
          'validators' => array('digits'),
          'filters' => array('digits')
            )), 

            'submit' => array('submit', array( 
                'label' => 'Send' 
            )) 
        ), 

As you can see, we added a filter to change the name field to all uppercase and another to strip out everything from the age that isn't digits. Now, when we submit these values, we see the results below.


Figure 3. The form with a filter applied
The form with a filter applied

When we hit Send, we end up with the following values after they pass validation and go through the filters, as shown below.


Figure 4. The form after validation and filters applied
The form after validation and filters applied

The age input, the filter, validator, and required attribute in that particular combination effectively guarantee a value will pass validation if and only if there's a digit in there somewhere and that no garbage that might have tried to get in with the digits will get passed through to the server. It should be noted that the only way to pass validation on the name field is to give it all alpha-characters to begin with because, in that case, the filter does nothing to help the value get past the bouncer.

Rendering the finished form can be accomplished in a few ways. The form has a render method that can be used or echoed directly. Most forms, however, use a Zend_View helper.



Back to top


Zend_Layout and Zend_View

The new Zend_Layout and the enhanced Zend_View components in Zend Framework V1.5 are often mentioned in the same breath and for good reason. Working together, these two components can be used to successfully decouple the presentation from the controller in PHP applications and standardize that presentation in such a way that facilitates rapid development and maintainability.

What does that all mean?

It means that a standardized and far less painful method of maintaining a consistent front end is now available, as long as you go along with the spirit of the thing and keep your code modular.

Zend_Layout does not have to be used with the Model-View-Controller (MVC). As with most of the Zend Framework, Zend_Layout can be pulled out and used on its own. However, when it is used with the MVC, it becomes a convenient sort of adapter between Zend_View and the controller, effectively compartmentalizing the presentation in a two-step view and making site layouts more universal.

Whether you are using the MVC or pulling out Zend_Layout as a stand-alone component, you will need to create at least one layout script. Sometimes called templates in other implementations, layout scripts define the basic front-end structure of a Web page, but instead of static data, they place variables on the page anywhere the displayed data may differ from page to page (or, more accurately: action to action). These placeholder variables in the layout script are populated by assigning the values needed in the layout script to the layout, telling the layout which particular layout script you want to use and finally rendering it as a page.

The actual rendering is done by Zend_View. So as far as Zend_Layout is concerned, you get all the Zend_View functionality for free. Layout scripts should be positively riddled with view helpers, or you're almost certainly not doing it right. View helpers are precisely where a significant portion of the convenience and standardization comes in to the mix.

When you have worked out your layout script(s), you can create an instance of Zend_Layout in your bootstrap and set your layout's configuration options. After it has been instantiated in this manner, you'll be able to access and reconfigure the Zend_Layout object from the action, via an action helper. Inside the action, you can change programmatically which layout script you want the instance of Zend_Layout to use, and re-populate the current variables each layout script will need. From the controller's perspective, all the data that ends up going to the user simply get shoved into a handy-dandy adapter, which takes it away to be used in an entirely different scope.



Back to top


OpenID and InfoCard (Web 2.0)

OpenID is a decentralized identification protocol designed to be used across many Web sites. Rather than require a correct username and password combination, the user is prompted for a URL or XRI, obtained from an existing OpenID provider. The provider performs the authentication. One way the providers are able to perform the authentication is by requesting an InfoCard. When the provider communicates successful authentication to the requesting site, that user is considered logged in, and additional information may be retrieved from his personal URL.

Zend Framework V1.5 supports the use of OpenID and InfoCard, not only as a client site but as an OpenID provider. These components are completely separate and have no dependencies on each other. Strange as it may seem, with Zend Framework V1.5, you may develop an OpenID provider that is not OpenID-enabled or vice versa (which makes more sense). There is also an InfoCard component built into the framework, which provides relying-party (or OpenID-enabled) support for InfoCards used in conjunction with OpenID.



Back to top


Lucene advanced searches

Lucene is an open source information-retrieval search engine, best known for its full-text indexing capabilities and its ability to search the Internet. The Zend_Search_Lucene component delivers the functionality of a built-in full-text advanced search engine to Zend Framework V1.5. It should be noted that while Lucene is a search engine, it has no crawling capability. You must manually add all relevant content into the Zend_Search_Lucene's index manually. (See Resources for developerWorks articles about Lucene.)

Zend Framework V1.5 is not the first appearance of the Zend_Search_Lucene component. A previous version of the search engine had already been implemented. However, the release of Zend Framework V1.5 does mark a significant upgrade from V1.9 to V2.2. With that upgrade, the Lucene component gained three powerful advanced-search options.

Both single and multiple wildcard searches are now supported, as are range searches and fuzzy searches. A range search will look for a value in a specified field between an upper and lower boundary, and a fuzzy search will look for words similar to the term supplied by the user. For instance, a fuzzy search on "Mike" might return "bike" and "mire."

While the Lucene component did get upgraded, the old functionality is still there, and all pre-existing indexes will be automatically upgraded the first time the enhanced Zend_Search_Lucene component touches them.



Back to top


LDAP authentication

Lightweight Directory Access Protocol (LDAP) has only just started to be supported in the Zend Framework. This is good news for quite a lot of developers who need to create, say, a company intranet application that uses an existing set of official company credentials. It is noted in the Zend Framework's current documentation that the current level of support is really just a bare-bones implementation, delivering just the minimum functionality required to be able to make Zend_Auth_Adapter_LDAP work.

In your config.ini file, information about your LDAP server is specified. When the user wants to authenticate, the supplied username and password combination, along with some additional Zend_LDAP options, are then sent to the LDAP server specified in the .ini file for authentication. Just like all the other authorization adapters, Zend_Auth_Adapter_Ldap returns a Zend_Auth_Result as soon as it's managed to get one from the server, with the following methods: getCode() will return a code for whatever happened (pass or fail); getIdentity(), which returns the identity of the authentication attempt; getMessages(), which will only contain messages on a failed authentication; and isValid(), which will return true if the user was successfully authenticated.



Back to top


Nirvanix, Technorati, and SlideShare Web services

Three new Web service components made their way into Zend Framework V1.5: Nirvanix, Technocrati, and SlideShare.

Nirvanix is an Internet-based file storage system that allows registered users to store, manipulate, and access files through their APIs. Nirvanix is designed to handle larger media files (such as video) and make them accessible anywhere you are able to authenticate over the Internet.

Technorati is a search engine for blogs, and its Web services allow you to make several different queries against their database, including regular keyword searches, tag searches, top-tag searches, sum totals of daily blogs featuring a given keyword, "cosmos" searches that return results that contain links to specific URLs. With Technorati, you will be able to quickly find out what's hot out on the wire today and stay on top of it.

Slideshare.net is a Web site that hosts slideshows for registered users. With the Slideshare component, you can embed slideshows hosted by slideshare within your PHP applications, view slideshows that have been shared with you, and upload new slideshows to your Slideshare account.

These three components join the list of Web services already supported by the Zend Framework. This growing library of Web-service components enables you to quickly and easily integrate content from more than a dozen popular Web sites into any PHP application. The fact that these Web-service components can be installed individually, without the presence of the rest of the Zend Framework, will be of particular appeal to those who are new to the world of PHP development, as well as seasoned PHP developers who simply prefer working in a different framework.

Next, we'll take look at feature enhancements that are noteworthy updates to features and components that existed before, but that needed to be modified to better address the new needs of the ever-changing Internet landscape.



Back to top


Google GData

The Zend_GData component is basically giant adapter for various Google services that support the GData API. The revised list of GData services accessible by the Zend_GData component includes:

  • Google Base
  • Google Blogger
  • Google Calendar
  • Google Codesearch
  • Google Documents List
  • Google Notebook
  • Google Provisioning
  • Google Spreadsheets
  • Picasa Web Albums
  • YouTube

Perhaps the most anticipated new Web service support in all of Zend Framework V1.5 is support for the YouTube API. Now, with Zend_GData, you can search through and access YouTube videos matching a large variety of criteria, access video feeds and subscriptions, look up user profiles, see all of a particular user's videos and favorites, and retrieve comments. With the existing functionality, appropriate YouTube content can be found and integrated seamlessly into your PHP applications.

Currently, the Zend Framework YouTube API support is read-only.

UTF-8 character support in Adobe PDF
Another improved feature in Zend Framework V1.5 is the addition of the UTF-8 character set to the native PDF support already provided by previous versions of the Zend Framework. This greatly increases the number of valid characters, and by extension, the number of languages supported by the PDF component. Additionally, it is now possible to extract fonts from loaded PDF files, making incremental updates a whole lot less painful to perform.


Back to top


Improved Ajax support: ContextSwitch helper and REST

Asynchronous JavaScript + XML (Ajax) has had a profound impact on the way information can be delivered to a client's browsing session. Very simply: With Ajax client-side JavaScript can request and receive information from an external source without navigating away from the main window location or reloading. Ajax is heavily used in Web applications like Gmail, which update information on a fairly constant basis without reloading the entire window.

Zend Framework V1.5 has improved native Ajax support with the ContextSwitch helper and the Zend_REST component.

The ContextSwitch helper, part of Zend_Controller, is used to deliver existing content in a different format or context. For instance, say you had constructed a controller to create a page, which lists in detail all the breakfasts you had consumed for the past three weeks. Normally, it would display the page with a layout and view consistent with the rest of your browser-friendly Web site. Now imagine someone in the world asks if you can serve up that same list in XML. With ContextSwitch, you no longer have to create a separate controller. Simply tell the helper that it can display XML and create an XML view script for it to use instead of the normal context view script. It will make sure the document extension and headers are all appropriate and well formed, and serve up all your breakfasts in Ajax-friendly XML.

And now it's even simpler than that: In Zend Framework V1.5, there is an AjaxContext helper that exists solely to switch context to XML specifically for the construction of Ajax responses.

The extended Ajax support continues to expand with the Zend_REST component, which contains both REST client and full REST server functionality. Zend_REST can be used to roll your own Web services or access and parse Web services. Of course, XML Web services you publish can be easily accessed with — you guessed it — Ajax.



Back to top


Summary

As we have seen, there are quite a few exciting new developments in Zend Framework V1.5. Some of the updates simply make routine tasks easier to set up correctly than they ever have been, and other updates make options readily accessible that would have been otherwise daunting at best to try and cook up by oneself. All of these things help to put more power in your hands, and that's never a bad thing.



Resources

Learn

Get products and technologies

Discuss


About the author

According to her mother, Katie Horn has spent far too much of her 28 years on the computer. She has a degree in computer science from Chapman University, after which she has mostly enjoyed the jobs with "systems" or "engineer" somewhere in the title. Despite a degree of proficiency in the area, she would prefer never again to be called "network admin."




Original link: http://www-128.ibm.com/developer...