Zend Framework and the New Hybrid Designer

Having a background in design, I’ve always felt a bit of a fake discussing web programming, however, the fact is that more and more designers are demonstrating that the whole left brain versus right brain, creativity versus logic idea is not as clear cut as is too often portrayed. While a good sense of aesthetics is important, it does not in itself directly equate to a well designed product. This is particularly true with web design, as a recent Web 2.0 Expo session entitled “The New Hybrid Designer” put it; “modern web design requires the coding savviness of a developer coupled with the aesthetics and user awareness of a designer”.

In this article I’d like to expand on an idea, put forward in that session, that choosing a decent platform or framework can provide an easier route into more productive development. The article is targeted at readers who already have experience working with PHP and are eager to improve their skills but don’t necessarily have the background to know what they should be learning.

Whether implementing contact forms, building templates for content management systems, setting up a forum, we are exposed more and more to the coding side of web design. Many of us find we cannot really be satisfied developing for the internet without learning a bit more about the engineering behind it. Unfortunately, our lack of formal software development training makes it harder to know which is the best approach. Often this results in, for example, hacking together one pre-built solution with another, only to realize how incompatible they are when asked to provide a single login for users. It is around this point when many of us start looking for a solution that helps to solve some of the core problems of web application development without having to be dismantled before doing so.

Given the title of this article, it is not surprising that the candidate I’m about to suggest for the position is the Zend Framework, however there are, of course, others. The arguments about the relative merits of one over another apply to application frameworks just as they do to preferences in text editors, image editors, programming languages, and so on. While we’re drifting off a little on that discussion it’s worth also considering something at an even lower level than the framework itself; the programming language in which it is written.

Before making a choice of framework the first question has to be which environment will it be developed in. Frameworks like Ruby on Rails, which is developed in Ruby, or Django, which is developed in Python, are undeniably capable frameworks, however the ubiquity of hosts providing setup and support for PHP, have it at a populist advantage. Unfortunately, as is often the case, popularity is no guarantee of quality and just as there is a great deal of development done using PHP, so is there a lot of lesser quality code and support. As a result, PHP, has acquired the unwarranted reputation of being a poor quality choice despite numerous high profile and high trafficked sites using it and talking about using it.

Having gained popularity, PHP has now moved to another level with PHP5 and will go further with PHP6, however, the fact is PHP5 is in many ways a new language for many PHP developers. Abstraction, interfaces, visibility, type hinting, exceptions, etc., are not new programming concepts, but being new additions to PHP, they introduce a level that can be quite challenging to many PHP developers. It is at this point that Zend Framework presents one of its key strengths; helping to leapfrog over the technical and into the practical.

Leapfrog the technical

This leapfrogging happens the moment you step into the framework since the basis for the structure of a Zend Framework site is the Model-View-Controller (MVC) design pattern. Studying design patterns can at the start feel like a journey way off the path of the practical until you actually begin to implement them. Even then it takes a while to feel confident that you’re using them correctly and appropriately. Zend Framework reflects the MVC pattern most evidently in its directory structure by dividing up code like so:

Put simply; models contains your domain specific code such as a user class, views contains your templates, or view scripts as they are called, and controllers contains the files that process data to and from the models and views. Following this simple practice not only introduces a design pattern into your programming arsenal, but also organizes your code in a way that makes it more maintainable than a great many existing PHP applications.

Of course “contains at least one recognized design pattern” is unlikely to ever be part of the client requirements for a project and their value is therefore not immediately obvious. The requirements that are obvious however, are often no less daunting, such as scalability, security, maintainability, flexibility and so on.

With web development moving more and more into the type of applications that would previously have been thought to require stricter languages like Java, so too has there been an improvement in the quality of web development platforms available. Some of the PHP frameworks have echoed the qualities of existing frameworks from other languages, such as Java’s Struts or Ruby-on-Rails, by reproducing them to one degree or another. In part contrast, Zend Framework, while undoubtedly drawing inspiration from existing frameworks, has been developed to make the most use of the improvements to the PHP language itself and in that regard acts not only as a building block for modern web applications but also as a learning tool.

One of the problems with designing object-oriented programs with PHP versions prior to PHP5 was that there were few ways to enforce any kind of contract or obligation between one object and another without resorting to hacks. This meant that code became fragile and scaling up and maintaining that code was more difficult. The following example provides a good opportunity to demonstrate how Zend Framework uses PHP5’s new object model to improve on that situation.

In the Zend Framework bootstrap file the front controller, itself another design pattern, has the job of directing traffic from the request to the response, the final part of that process is dispatching. You’ll notice that the parameters of the dispatch() method are preceded by class names:

Those class names are type hints whose role is to ensure that the parameters they precede are only ever instances of those classes. Why you would need to do that becomes clearer further on in the dispatch() method when, for example, a method call is made on the $request object:

Had we not ensured that $request was an instance of Zend_Controller_Request_Abstract we would would have had no way of guaranteeing that it even had the setBaseUrl() method to call. At first glance this may appear overly restrictive, particularly if you want to use your own request or response objects, until you notice that the class name is appended with the word Abstract. This unofficial Zend Framework naming convention indicates that the class is an abstract class. Having the type hinting specify an abstract class forces the object passed into dispatch() to have extended that abstract class and therefore ensuring that it contains any needed methods or properties while also allowing it to be a custom class.

By following the principle of programming to an interface, not an implementation, not only has this combination of type hinting and abstract classes allowed two objects to work together but it has also done so in a way that means that neither is dependent on any particular implementation of the other. I can even send my two unlikely request and response objects; Nicks_Controller_Request_LunchOrder and Nicks_Controller_Response_DeliciousLunch, to dispatch() as long as they are both subclasses of the abstract classes Zend_Controller_Request_Abstract and Zend_Controller_Response_Abstract respectively.

Security

Thankfully, the importance of the security of web applications has been gaining more public attention in the past few years and while there is a wealth of information available it’s still a daunting responsibility. PHP5’s introduction of features such as the ability to limit access to properties and methods with the public, protected and private keywords are good language level guides, but don’t in themselves ensure secure programming. Securing your application means not only developing good coding habits but also generally requires additional code, both of which can be undermined by the pressures of a tight deadline. Team based development also introduces the additional element of security holes slipping in due to inadequate guidelines or miscommunication.

Davey Shafik’s escaping and filtering cheat sheet is a great visual overview of the ways to deal with potentially tainted data and the Zend Framework again develops on the language level functionality with a series of components. For filtering input, such as an ID from a $_GET request, we can use Zend_Filter:

More useful is the ability to build chains of multiple filters:

Some data requires validation such as email addresses, credit card numbers or simply making sure a username is of a certain format. For this we have Zend_Validate to which we can also chain like Zend_Filter:

This combination of chainable filters and validators as illustrated above, together with the ability to easily add our own custom filters and validators, provides a very competent and flexible way to manage incoming data. Often the data we are filtering is heading for a database and Zend_Db has that in hand, adding a further protective layer with features such as Zend_Db_Adapter’s quote() and quoteInto() methods or an even better example; using bound parameters:

Of course it’s possible that in many cases the perpetrator should have been stopped from gaining access to the means to submit any of the above data. For this reason, we have the ability to authenticate their identity, eg against a database, with Zend_Auth and the power to control the subsequent access to the application using access control lists in Zend_Acl.

Having done all we can to stop bad things getting in, we cannot then ignore the output we are producing, most often through views. Zend_View contains its own output filter in its escape() method. After filtering output through PHP’s htmlspecialchars() and htmlentities() and any other custom methods specified via Zend_View::setEscape() it can be used in view scripts like so:

Back to Aesthetics

Programmers are as equally attracted to the aesthetics of good looking code as designers are to well set type. We’d all quickly run out of fingers and toes counting the amount of times we’d had to try and read code (including our own) that makes our eyes burn! However, trying to define the coding standards for a team is often a contentious issue and arguments about, e.g. which brace style to use, naming conventions, tabs versus spaces, etc., can be difficult to resolve, as each programmer may have different reasons, such as screen size, tool settings, etc. Using the pre-determined coding standard of a framework is a simple way of getting a consensus. Like others, Zend Framework has a well documented coding standard and if you or any of your team members feel the need to argue about it they are free do so on the mailing list rather than amongst yourselves. Talking about team based development and aesthetics brings up another benefit of the MVC structure of the Zend Framework I mentioned earlier; its separation of the views from the controllers and models. Aside from code required to render elements in the template, such as looping over a results set to generate a table, an interface designer should not be required to know PHP to work with the view element of the application. As I illustrated earlier Zend_View uses PHP itself as the “template engine” but integrating other engines like Smarty can and has been done.

A further less obvious aesthetic can be found in Zend Framework’s ability to produce clean, or “cruft-free” as the Django project refers to them, URL’s. An url like…

…is clearly preferable visually and semantically to…

…but the former often required some complex Apache mod_rewrite rules.

Having what are in many ways the API to your web application stored outside the application in .htaccess files is also less satisfactory than having them kept within the application. With the routing capabilities provided in the MVC components of Zend Framework your application has the means to produce much more sustainable and in certain cases search engine optimized URLs. This is also useful when upgrading older sites with established URLs to your shiny new Zend Framework based site.

Where are the showcases?

If you’ve already looked over the Zend Framework you may have noted that in this article I’ve not mentioned any of what could be seen as the more showcase features such as; its collection of Web services tools like Zend_Gdata, Zend_Feed, and Zend_Service_*; Zend_Search, its implementation of the Lucene text search engine; its answer to internationalising your application with Zend_Translate, Zend_Locale and related components like Zend_Date; its improvements to PHP’s own session handling with Zend_Session; not to mention future components being worked in its incubator. The reason I didn’t go into all these is partly as each is an article in its own right but also because I wanted to illustrate the effect of using a framework in improving the quality of the more mundane programming work we have to do.

Zend Framework provides a well constructed approach to web development that not only takes advantage of the improved features of PHP5 but also incorporates the practices of good object-oriented design. It is for this reason that I would recommend it to any PHP developers fitting the description I gave at the start of this article.