10 Compelling Reasons to Use Zend Framework


Trying to decide which framework to use for your new project? In this article, we’ll go in-depth about why Zend Framework should absolutely be your PHP framework of choice.


Introduction

Whether you’re starting a new project or improving an existing one, in this article, I’ve provided 10 reasons why you should use Zend Framework for your next project, and hopefully, it helps you in making an informed decision.


Reason 1. Extend classes like there’s no tomorrow

Zend Framework is a fully object-oriented framework, and as such, it utilizes a lot of object-oriented (OO) concepts like inheritance and interfaces. This makes most, if not all, of ZF’s components extendable to some point. It allows developers to implement their own special variations of individual components without having to hack into the ZF codebase itself. Being able to customize ZF this way allows you to create functionality that is unique to your project, but because of its object-oriented nature, you’ll be able to use this functionality in other projects as well.

Example

Zend Framework has a very extensive Validation component, which you can use to validate data coming from forms. In ZF, forms are treated as objects as well, and are represented by the Zend_Form component.

Let’s assume that you want to create a custom URL validator to restrict URL input from the user. The quickest way to do this would be to just validate the input using something like:

$isValid = filter_var($submitted_url, FILTER_VALIDATE_URL);

But this won’t adhere to the OO nature of form objects, since it’s not used within the context of the form. To solve this, we can create a new Zend_Validator class by extending the Zend_Validate_Abstract class:

<?php
class Zend_Validate_Url extends Zend_Validate_Abstract
{
	const INVALID_URL = 'invalidUrl';

	protected $_messageTemplates = array(
		self::INVALID_URL   => "'%value%' is not a valid URL.",
	);

	public function isValid($value)
	{
		$valueString = (string) $value;
		$this->_setValue($valueString);

		if (!Zend_Uri::check($value)) {
			$this->_error(self::INVALID_URL);
			return false;
		}
		return true;
	}
}

This actually uses the Zend_Uri class, which already has a URL checking method we can use. But since it doesn’t extend the Zend_Validate_Abstract class, we implemented a wrapping class which does implement the needed abstract class. This lets us use the Zend_Uri URL checking function in our Zend_Form objects like so:

<?php
class Form_Site extends Zend_Form
{
	public function init()
	{
		$this->setMethod('POST');
		$this->setAction('/index');

		$site= $this->createElement('text', 'siteurl');
		$site->setLabel('Site URL');
		$site->setRequired(true);

		//  Adding the custom validator here!
		$site->addValidator(new Zend_Validate_Url());
		$this->addElement($site);
		$this->addElement('submit', 'sitesubmit', array('label' => 'Submit'));
	}

}

If we wanted to check that our URLs are valid YouTube video URLs, we could do something like this:

<?php
class Zend_Validate_YouTubeUrl extends Zend_Validate_Abstract
{
	const INVALID_URL = 'invalidUrl';

	protected $_messageTemplates = array(
		self::INVALID_URL   => "'%value%' is not a valid URL.",
	);

	public function isValid($value)
	{
		$valueString = (string) $value;
		$this->_setValue($valueString);

		if (strpos($value, "http://www.youtube.com/watch?v=") !== 0) {
			$this->_error(self::INVALID_URL);
			return false;
		}
		return true;
	}
}

If we added this to our site form object as a validator, it would ensure that all URLs submitted begin with the correct YouTube video URL prefix.


Reason 2. Object-oriented Goodness


Image courtesy of http://www.developer.com

In Zend Framework, everything is an object, as proven by our example above. This poses its own disadvantages, such as making things more complicated to code. Its main advantage, though, is the ability to make code reusable, and since nobody likes to repeat themselves, this is a very good thing.

Example

We already have our Zend_Validate_Url and Form_Site class from our example above, so let’s reuse them in this example.

<?php

class IndexController extends Zend_Controller_Action
{

    public function indexAction()
    {
		$siteform = new Form_Site();

		if( $this->_request->isPost() && $siteform->isValid($this->_request->getPost()) ) {
			//stuff to do if the input is correct
			$this->_redirect("/index/correct");
		}
		$this->view->siteform = $siteform;
    }

    public function correctAction()
    {
		// Yay, we're re-using our Form_Site object!
		$this->view->siteform = new Form_Site();
    }
}

Here’s what it would look like on a browser:

If you tried to submit an invalid URL, you can see our URL validator at work:

Here, you can see what would happen if you did input a valid URL:

As you can see, we’ve never had to repeat our form object code.

“Zend_Validate classes can be used in other ways as well, not only within the context of Zend_Form classes. You simply instantiate a Zend_Validate class and call the isValid($parameter) method, passing it the value you want to validate.”


Reason 3. Use What you Need, Forget Everything Else

Image courtesy of http://dev.juokaz.com

By design, Zend Framework is simply a collection of classes. Normally, you’ll use Zend MVC components to create a fully-functional ZF project, but in any other case, you can just load the components you need. ZF is very decoupled, which means we can take advantage of the components as individual libraries, instead of the framework as a whole.

If you’ve been looking at other framework articles, you’ve probably heard of the term glue framework. ZF, by default, is a glue framework. Its decoupled nature makes it easy to use as “glue” to your already existing application.

There’s a debate between using glue frameworks vs. full-stack frameworks. Full-stack frameworks are those that provide you everything you need to create your project, like ORM implementations, code-generation, or scaffolding. Full-stack frameworks require the least amount of effort to create a project, but fall short in terms of flexibility, since it imposes strict conventions on your project.

Example

Let’s say you need a way to retrieve information about a specific video on YouTube. Zend_Gdata_Youtube is a ZF component which allows you to access data from YouTube via the GData API. Retrieving the video information is as simple as:

//Make sure you load the Zend_Gdata_Youtube class, this assume ZF is in your PHP's include_path
include_once "Zend/Gdata/Youtube.php";

$yt = new Zend_Gdata_YouTube();
// getVideoEntry takes in the YouTube video ID, which is usually the letters at the end
// of a YouTube URL e.g. http://www.youtube.com/watch?v=usJhvgWqJY4
$videoEntry = $yt->getVideoEntry('usJhvgWqJY4');
echo 'Video: ' . $videoEntry->getVideoTitle() . "<br />";
echo 'Video ID: ' . $videoEntry->getVideoId() . "<br />";
echo 'Updated: ' . $videoEntry->getUpdated() . "<br />";
echo 'Description: ' . $videoEntry->getVideoDescription() . "<br />";
echo 'Category: ' . $videoEntry->getVideoCategory() . "<br />";
echo 'Tags: ' . implode(", ", $videoEntry->getVideoTags()) . "<br />";
echo 'Watch page: ' . $videoEntry->getVideoWatchPageUrl() . "<br />";
echo 'Flash Player Url: ' . $videoEntry->getFlashPlayerUrl() . "<br />";
echo 'Duration: ' . $videoEntry->getVideoDuration() . "<br />";
echo 'View count: ' . $videoEntry->getVideoViewCount() . "<br />";

Code sample courtesy of Google Developer’s Guide

This code would output:

One thing to note here: this Zend Framework component (GData) is the official PHP library endorsed by Google to access its API. The framework’s decoupled nature allows us to use the component in any project, regardless of the framework we used to build it.


Reason 4. It lets you do a Lot of Things!

One of the things I love most about Zend Framework is that it has A LOT of components. Need a way to authenticate a user? Use Zend_Auth. Need to control access to your resources? Look up Zend_Acl. Need to create some forms? We have Zend_Form. Need to read an RSS feed? You can use Zend_Feed for that. It’s basically the Swiss Army knife of PHP classes!

Zend actually comes with some demos that show how to use its different components:

To view these, the best way is to simply download the Full Package Version of Zend Framework and test them out on your machine.

For a complete list of all the components, you can check out the Zend Framework Manual.


Reason 5. No Model Implementation – Choose your Own Adventure!

Image courtesy of http://www.vintagecomputing.com

This is actually one of the reasons most developers don’t use Zend Framework – it has no Model implementation on its own. For those who don’t know what a Model is, it’s the M in MVC, which stands for “Model-View-Controller”, a programming architecture that’s used by most PHP Frameworks.

Does that mean that Zend Framework is only a “VC” Framework?

Yes, and no.

Yes, it’s a VC framework because it doesn’t have its own Model implementation. This makes it hard for some people to use ZF, especially if they’re coming from a framework which does have a Model implementation (like CakePHP, Symfony, or even Ruby on Rails).

On the other hand, no, it’s an MVC framework as well, since apart from providing the generic ways to access the database (using Zend_Db), it actually still relies on some sort of Model implementation. What it does differently is that it leaves this kind of implementation up to the developer ñ which some say should be the case since models are actually where the business logic of the application resides, and therefore, they’re not something which can be developed as a generic component. Zend Framework Philosophy states that model implementations are unique to the projectóit’s impossible to create an abstract implementation of it since they don’t really know what you need. They believe that models should be implemented by the developers themselves.

How is this a good thing?

Not having a Model implementation means that the developer is free to use whatever means he has to implement it, or even just integrate existing implementations. Being free of predefined restraints, the developer is then allowed to create more complex implementations, rather than just simple representations of tables, which is how usual Model implementations are created. Models contain your business logic. They should not be restrained by your database tables; rather, they should dictate the connections of these tables to one another. This lets you put most of your programming code in your Models, therefore satisfying the “Thin Controllers, Fat Models” paradigm of MVC.

So how will I use Zend Framework if I have no idea how to create my own models?

For beginners, the Zend Framework Quickstart tutorial shows us a good way to implement models. In the tutorial, they implement an ORM approach to the models, wherein you would create three filesóthe actual Model, which is an abstract representation of your object; a Mapper, which maps data from the database to your Model; and a Database Table object, which is used by the mapper to get the data. You can check out the code in the ZF Quickstart tutorial, where they used this approach to implement the model of a simple Guestbook application.

For those asking “Why do I have to code this myself while other frameworks do the work for me?”, this is a perfect segue to my next reason…


Reason 6. Integrate with Whatever you Want!

Zend Framework’s decoupled nature makes it very easy to integrate other libraries that you want to use. Let’s say you want to use Smarty as your templating system. It can be done by simply creating a wrapping class for Zend_View_Abstract, which uses a Smarty instance to render the view.

This works both ways, as you can integrate ZF into other libraries as well. For example, you can integrate ZF into Symfony. They’re planning to do this with Symfony 2, using the Zend_Cache and Zend_Log components from ZF.

Example

For our example, we’ll try using Doctrine to implement our Model. Continuing from our site example above, say you’ve already implemented your DB table like so:

CREATE TABLE  `site` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `url` varchar(100) CHARACTER SET latin1 NOT NULL,
  PRIMARY KEY (`id`)
);

To integrate Doctrine into ZF, we’ll have to make sure that the proper settings are defined. I’ve followed this tutorial from dev.juokaz.com about using Doctrine with ZF.

Assuming everything works out, you’ll just have to generate your model files by running the doctrine-cli.php php file from the tutorial like so:

php doctrine-cli.php generate-models-db

You should see this success message:

Afterwards, you can check the folder which you set as the place to store the generate Model classes.

Then in our controller class, we can simply use our site model class.

<?php

class IndexController extends Zend_Controller_Action
{

    public function indexAction()
    {
		$siteform = new Form_Site();

		if( $this->_request->isPost() && $siteform->isValid($this->_request->getPost()) ) {
			//stuff to do if the input is correct
			$site = new Model_Site();
			$site->url = $this->_request->getParam('siteurl');
			$site->save();
			//redirect to our success page
			$this->_redirect("/index/correct");
		}
		$this->view->siteform = $siteform;
    }

    public function correctAction()
    {
		// Yay, we're re-using our Form_Site object!
		$this->view->siteform = new Form_Site();
    }
}

If we check our sites table, we’ll see that our records is there

Now, every time we submit a site, our controller will use our Doctrine model implementation to save to our database. Isn’t that nice and easy? Setup may be a bit complicated, but on the plus side, our project is now able to take advantage of a tool which has been developed specifically for Model implementation. Our project now has the power of two very developed technologies behind it.


Reason 7. Guidelines and Standards

Zend Framework is developed in conjunction with a very extensive Contributor Guide, which basically states that:

  1. Every contributor for both documentation and/or code, at any level (either a few lines of code, a patch, or even a new component) must sign a Contribute License Agreement (CLA).
  2. Code MUST be tested and covered by a unit test using PHPUnit. And…
  3. Code must adhere to strict Coding Standards

These strict guidelines ensure that you only use readable, high-quality code that has been tested thoroughly.


Reason 8. All Code is Guilty Until Proven Innocent (aka Test-Driven Development)

Image courtesy of http://www.codesmack.com/

Test-driven development is a programming technique that requires a developer to write tests for the function he is supposed to code before writing code for the function itself. By writing the tests first, it ensures that the programmer:

  1. Thinks of the possible use-cases of his code
  2. Creates a whitelist of input and output
  3. Makes it easier to refactor his code
  4. Makes it easier to pass code from one person to another

The test-driven development Cycle
Image courtesy of Wikipedia

Zend Framework makes it easy to do TDD via Zend_Test, which uses PHPUnit, a popular unit testing framework. PHPUnit lets you test not only your Controllers, but also your library and model functions. To add to this, Zend_Tool, which is Zend Framework’s scaffolding utility, already makes provisions for PHPUnit when you use it to create your project.

Integrating PHPUnit and Zend Framework

Setting up Zend Framework and PHPUnit is not that difficult. Basically, once you’re done with it, you’ll be able to use the same setup for your future projects. Just as a side note, the following steps assume that you’ve used Zend_Tool to scaffold your project structure and files, but it should be relatively simple to change for other setups.

First, we need to install PHPUnit. The best way is to install it via PEAR:

pear channel-discover pear.phpunit.de
pear install phpunit/PHPUnit

Afterward, we’ll open our phpunit.xml, an XML file generated by Zend_Tool. You’ll find it inside the tests folder in the root directory of your project. Add the following lines:

<phpunit bootstrap="./TestHelper.php" colors="true">
    <testsuite name="Zend Framework Unit Testing">
        <directory>.</directory>
    </testsuite>

    <filter>
        <whitelist>
            <directory suffix=".php">../library</directory>
            <directory suffix=".php">../application</directory>
            <exclude>
                <directory suffix=".phtml">../application</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>

After saving phpunit.xml, create a new file inside the same folder as phpunit.xml called TestHelper.php. This PHP file will help us setup the environment for our tests.

<?php
// start output buffering
ob_start();

// set our app paths and environments
define('BASE_PATH', realpath(dirname(__FILE__) . '/../'));
define('APPLICATION_PATH', BASE_PATH . '/application');
define('APPLICATION_ENV', 'testing');

// Include path
set_include_path(
    '.'
    . PATH_SEPARATOR . BASE_PATH . '/library'
    . PATH_SEPARATOR . get_include_path()
);

// We wanna catch all errors en strict warnings
error_reporting(E_ALL|E_STRICT);

require_once 'ControllerTestCase.php';

We then create our parent Controller Test Case class, which all of our Controllers will extend. This will help implement methods which would usually be the same throughout all of the Controller test classes.

<?php
require_once 'Zend/Application.php';
require_once 'Zend/Test/PHPUnit/ControllerTestCase.php';

abstract class ControllerTestCase extends Zend_Test_PHPUnit_ControllerTestCase
{
    public $application;

    public function setUp()
    {
        $this->application = new Zend_Application(
            APPLICATION_ENV,
            APPLICATION_PATH . '/configs/application.ini'
        );

        $this->bootstrap = $this->application;
        parent::setUp();
    }

    public function tearDown()
    {
        $this->resetRequest();
        $this->resetResponse();
        parent::tearDown();
    }
}

Lastly, we create a controller test class:

<?php
require_once realpath(dirname(__FILE__) . '/../../ControllerTestCase.php');

class IndexControllerTest extends ControllerTestCase
{
    public function testCallingRootTriggersIndex()
    {
        $this->dispatch('/');
        $this->assertController('index');
        $this->assertAction('index');
    }

    public function testCallingBogusTriggersError()
    {
        $this->dispatch('/bogus');
        $this->assertController('error');
        $this->assertAction('error');
        $this->assertResponseCode(404);
    }
}

All that’s left is to run our test. Open your command prompt and go to the tests folder and type:

phpunit

Your command line should output the following:


PHPUnit and Zend Framework setup tutorial and code courtesy of http://www.dragonbe.com

Reason 9. Community and Documentation

Due to its multiple components, complexity, and fully object-oriented approach, Zend Framework has a very steep learning curve. It becomes easier to learn due to the comprehensiveness of its documentation and its thriving community. First of all, the Zend Framework Programmer’s Reference Guide boasts a complete guide to all ZF components, with examples, code, and usage theories.

Aside from this, there are a lot of blogs out there that share Zend Framework tips and tricks. For example, Phly, boy, phly, the blog of Matthew Weier O’Phinney, a Core Contributor to Zend Framework, provides a lot of insights, clever uses, and component explanations for Zend Framework. Zend also has a site called Zend Developer Zone, which aside from publishing tutorials for Zend Framework, has stuff like Zend Framework Webinars, podcasts, and articles about PHP in general. Another site, called Zend Casts, offers a lot of useful video tutorials on different Zend Framework components as well. Last but not least, there’s a free online book called Zend Framework: Surviving the Deep End” written by P·draic Brady, another Zend Framework contributor.

As you can see, there is no lack of support from the community, the documentation, and the developers. If you have any questions or need any clarifications, a quick search with the right keywords should almost always give you relevant results. If not, there’s still the Zend Framework Mailing Lists, the official Zend Framework Forums, the unofficial Zend Framework Forums or the unofficial Zend Framework IRC channel


Reason 10. Certifications Ahoy!

If you’re still unconvinced about learning and using Zend Framework, this reason is actually the one that I feel most distinguishes Zend Framework from all the others. Zend not only offers Zend Framework Certification, but PHP Certification as well. By offering certifications, Zend helps you use your expertise in PHP and Zend Framework to boost your portfolio or CV. The Zend Certification site lists a number of reasons to get certified, some of which are:

  1. Differentiate yourself from competitors when looking for a new job
  2. Get your resume/CV noticed
  3. Have your profile displayed in Zend’s Yellow Pages for PHP Professionals
  4. Be part of the Linkedin Group Exclusively for ZCE’s
  5. Get special discounts on Zend PHP conferences worldwide

Addendum

Just to keep things balanced, here’s a quick list of reasons why you might not want to use Zend Framework:

  1. VERY steep learning curve. It’s not very hard for advanced PHP users, but for beginners, there’s a lot to learn!
  2. Big footprint. Since Zend Framework has a lot of components, it’s total size is relatively higher than other Frameworks. For example, CodeIgniter’s system folder has a 1.5MB footprint compared to Zend Framework’s 28MB footprint.
  3. No solid scaffolding tool. Although Zend_Tool offers some functionality, it’s not much compared with the scaffolding utilities of full-stack frameworks like CakePHP or Symfony.
  4. Not shared webhosting friendly. The folder structure generated by Zend_Tool suggests that the public folder be the only directory accessible via http ó which assumes that a user is able to create a virtual host for the project. This is something you aren’t able to do in most shared web hosting environments.
  5. Too gluey. Since everything is in separate classes, it’s sometimes hard to envision how everything works. This wouldn’t be a problem with full-stack frameworks, since they mostly take care of everything for you. Without Zend_Tool, it would be extremely difficult to set up a working project structure

Conclusion

A lot of advancements have been made in the world of PHP Frameworks in the past few years. I’ll be honest, there’s a whole lot of fish in the sea. There are frameworks like Codeigniter, CakePHPand Symfony which are also good to use. Some of you might be thinking, “Why did this guy focus on Zend Framework? Why didn’t he run performance tests to compare the different frameworks?” To that, I reply with this quote from a very entertaining article entitled “PHP Framework Benchmarks: Entertaining But Ultimately Useless” by P·draic Brady:

To create a positive benchmark, you need to understand that all frameworks were born as festering piles of unoptimised stinking crap. They were all born bad and get worse with age. This sounds quite sad, but actually it’s an inevitable compromise between performance and features. It’s also a compromise between performance and ease-of-use. So you see, performance is unfairly faced by two opponents: features and ease-of-use. All performance is sacrificed in the name of serving the needs of rapid development, flexibility, prototyping, and making your source code look prettier than the other guy’s. As if.

What happens if you move away from the enemies of performance and do some propping up behind the scenes? You get…wait for it…oodles of extra performance!

When it comes down to it, which framework you choose to use really depends on how comfortable you are with it. None of these frameworks would be of help to you if you aren’t able to take full advantage of their features. You can spend weeks or even months using a specific framework, only to trash it in the end because you just aren’t as comfortable using it as you were with some other framework.

So I invite you to at least try out Zend. If it works for you, that’s great! It does for me. But if it’s not a good fit, go ahead and try out the others. Soon enough, you’ll find the framework that’s just right for your needs.

Leave a Reply

Your email address will not be published. Required fields are marked *