What’s New in Zend Framework 2

Tweet

When I started writing for SitePoint, one of my first articles was about Zend Framework. Since then, the framework has released version 2 stable. Apart from the name, version 2 is really a new project compared to the older version; ZF has been totally rewritten. In this article I’ll give you an overview of the new features and the changes that have been introduced.

Packaging System

You’ve up to four different ways to obtain ZF2. The first is the classic way, downloading one of the packages available from the website’s download page or from packages.zendframework.com. The second is similar, but you can download it from the ZF GitHub repository. The third is by using Composer, a tool for dependency management. To install ZF2 using Composer, add the following lines to your composer.json file:

"repositories": [
  {
    "type": "composer",
    "url": "https://packages.zendframework.com/"
  }
],

"require": {
  "zendframework/zend-config": "2.0.*",
  "zendframework/zend-http": "2.0.*"
}

The forth method is to use PEAR2_Pyrus, running these commands:

pyrus.phar .
pyrus.phar . channel-discover packages.zendframework.com
pyrus.phar . install zf2/Zend_Framework#Standard

For version 2, ZF has developed and released a base skeleton application to get you started, with which you can start developing your own. You can download it from GitHub or using Composer:

composer.phar create-project --repository-url="http://packages.zendframework.com" zendframework/skeleton-application path/to/install

Autoloading System

ZF2 seems to provides you with a lot of different alternatives for every new feature. The autoloading system, for example, now has three different options. You’ll see that there’s no trace of the require_once lines that were heavily used in the first version. Of course, a single require_once is needed to enable the new autoloading system, the one for the autoloader. The code to use should resemble the following:

<?php
require_once 'Zend/Loader/StandardAutoloader.php';
$autoLoader = new ZendLoaderStandardAutoloader(array(
    'fallback_autoloader' => true,
));
$autoLoader->register();

This method loads namespaced classes using the PSR-0 standard (a great discussion on PSR-0 has been written by Hari K T in his article entitled Autoloading in PHP and the PSR-0 Standard). Note that setting 'fallback_autoloader' => true enables a fallback that allows you to invoke the PHP default inclusion system to include those files that don’t fall in the Zend namespace.

The second method is based on a class map, a file with an associative array where the keys are the class names and the values are their absolute path. Being that the class map is a simple file that returns absolute paths, this method can be faster compared to the previous one, up to 20% in its standard usage or up to 80% using an opcode cache system like APC. What’s tedious in this system is the creation of the map file itself, especially for larger projects. Luckily the ZF team created a class map generator that can automatically build the map for you. By default it’ll search for files into the current directory and write the output in a file created in the specified path. An example of its use is:

php classmap_generator.php My/Project

However, you can configure the script. For an overview of the options available, take a look at the class map generator documentation.

The third method is quite similar to the first. What changes in this case is that you can specify the path of the files using a given namespace like the examples below.

<?php
require_once 'Zend/Loader/StandardAutoloader.php';
$autoLoader = new ZendLoaderStandardAutoloader();
$autoLoader->registerNamespace('ApplicationNamespace', 'Path/to/files');
$autoLoader->register();

Or, you can set a specific prefix.

<?php
require_once 'Zend/Loader/StandardAutoloader.php';
$autoLoader = new ZendLoaderStandardAutoloader();
$autoLoader->registerNamespace('FilesPrefix_', 'Path/to/files');
$autoLoader->register();

Dependencies System

The developers tried to write code so it was as decoupled as possible and, to achieve this goal, the new version has been developed following the Inversion of Control (IoC). As Wikipedia states, IoC is “a programming technique, expressed in terms of object-oriented programming, in which object coupling is bound at run time by an assembler object and is typically not known at compile time using static analysis.” For a good explanation on this pattern, I suggest you take a look at Alejandro Gervasio’s article Inversion of Control – The Hollywood Principle.

Event Manager

The last feature I’d like to discuss in this article is the new Event Manager implemented by the class ZendServiceManager that replace the component ZendApplication of the previous 1.x version. ZF2 is, in fact, now event-driven. As you might already know, before actually running the controller’s action, the framework does a lot of things. The first is to run the bootstrap which sets up the app modules and configuration. After the bootstrap, the URL requested by the user is parsed to route the application in the right way (usually module/controller/action) and then starts the dispatcher. In each of these steps you have a set of events that you can manage in almost any way you like to change the application flow.

You can add events through the attach() method of the EventManager class. It accepts the name of the event to listen for, a callback function to call when the event is fired, and an (optional) parameter that specifies the event’s priority. The latter is specified by a positive integer that by default is 1. The higher the number, the higher the priority and earlier the execution.

The event can be called using the trigger() method that also belongs to EventManager. Its parameters are the name of the event to fire, the context which is usually an instance of the object who has the event (or null if you use an anonymous function), and an array containing parameters to pass to the event handler. A simple example is the following:

<?php
// Attach the handler
$event = new EventManager();
$event->attach(
   'myEvent',
   function($event) {
      $parameters = $event->getParams();
      echo 'The given name is ' . $parameters['name'] . ' ' . $parameters['surname'];
   },
   100
);

// Fire the event
$parameters = array('name' => 'Aurelio', 'surname' => 'De Rosa');
$event->trigger('myEvent', null, $parameters);

Conclusions

Throughout this article you learned about the major changes in Zend Framework 2. To sum things up, these are the key points I discussed:

  • New packaging system, based on composer and pyrus, to download and install
  • New MVC architecture based on events
  • Better performance
  • New autoloading class system
  • ZF2 uses several new design patterns like Event Manager and Dependency Injection that help you to decouple your code

You may be overwhelmed by all these changes, and I think this is not so strange due the wide range of new features and improvements that have been introduced. In fact, this article just skims the surface. Feel free to download a copy of the framework and explore.

Image via Fotolia

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Nicky De Maeyer

    Better performance is theoretic, in practice all benchmarks have shown it to be slower then ZF1. (Using simple hello world,in mvc)

  • Uncle Fred

    ZF2 is a strange beast, but no other framework gets me so excited and fits my understanding of “how it should be done” and more. You have plenty things to discover and hopefully we’ll see more articles about it. Good start however.

  • http://zf2book.com Michael

    I recently released my book “Web Development with Zend Framework 2″ on Leanpub (http://leanpub.com/zendframework2-en). It might be of help to developers starting with ZF2. Thanks!

  • CMB

    There is no sense to benchmark a MVC framework with a simple “Hello World!”.

    • http://www.audero.it/ Aurelio De Rosa

      I agree with you.

  • Big Sheep

    with ajax you do not go much further than “hello word”, it makes sense to do a benchmark. But, i agree that’s not enough to know if a framework is good or not.

  • http://okeowoaderemi.com okeowo aderemi

    Aurelio which Zend 2 books can you recommend, 2013 is meant to be dedicated to this Framework but its hard understanding some stuff,i usually just read the source code.

    • http://www.audero.it/ Aurelio De Rosa

      Honestly I haven’t seen a book on Zend Framework 2 yet so I can’t suggest you a title.

  • Eubby

    Hi, i’m coming from ci and i’ve just started learning zf1. Do you think I should continue to learn zf1 or start learning zf2 now?

    • http://www.audero.it/ Aurelio De Rosa

      Honesly I think you should switch to Zend Framework 2.

  • DNoe

    There doesn’t seem to be much here about Zend Framework 2. Is that going to change?

    • http://www.bitfalls.com/ Bruno Skvorc

      Here meaning on SitePoint in general?

      • DNoe

        Yes, on SitePoint. Not this article specifically.

        • http://www.bitfalls.com/ Bruno Skvorc

          We can definitely make an effort to push more ZF content, yes, I’ll conjure up some topics. If there’s any specific use cases you’d like covered, please do feel free to let me know via google.com/+BrunoSkvorc and I’d be happy to make sure it happens.