Introduction
Whether you’re starting a new project or improving an existing one, in this article, I’ve provided ten 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
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);
- <?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;
- }
- }
- <?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'));
- }
- }
- <?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;
- }
- }
Reason 2. Object-oriented Goodness
Image courtesy of http://www.developer.com
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();
- }
- }
“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
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 />";
This code would output:
Reason 4. It lets you do a Lot of Things!
Zend actually comes with some demos that show how to use its different components:
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!
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!
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`)
- );
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
- <?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();
- }
- }
Reason 7. Guidelines and Standards
- 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).
- Code MUST be tested and covered by a unit test using PHPUnit. And…
- Code must adhere to strict Coding Standards
Reason 8. All Code is Guilty Until Proven Innocent (aka Test-Driven Development)
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:
- Thinks of the possible use-cases of his code
- Creates a whitelist of input and output
- Makes it easier to refactor his code
- Makes it easier to pass code from one person to another
Integrating PHPUnit and Zend Framework
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
- <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>
- <?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';
- <?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();
- }
- }
- <?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);
- }
- }
phpunitYour command line should output the following:
Reason 9. Community and Documentation
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!
- Differentiate yourself from competitors when looking for a new job
- Get your resume/CV noticed
- Have your profile displayed in Zend’s Yellow Pages for PHP Professionals
- Be part of the Linkedin Group Exclusively for ZCE’s
- 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:- VERY steep learning curve. It’s not very hard for advanced PHP users, but for beginners, there’s a lot to learn!
- 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.
- 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.
- 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.
- 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
No comments:
Post a Comment