Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

A Zend Framework 2 tryout

DZone's Guide to

A Zend Framework 2 tryout

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

Zend Framework 2 is probably the likely upgrade for applications based on Zend Framework 1. This new generation of PHP frameworks - built on PHP 5.3 and lead by Symfony 2 - is going to replace their older versions in the next years.

Diving into the code

Since I have much familiarity with Zend Framework 1, I decided to jump into the 2.x beta version to discover what has changed and how it does impact my existing applications.

Rob Allen's step by step tutorial is probably the point of entry, also for people who have never used Zend Framework. You can installation via git cloning (or by grabbing a zip) a skeleton application ready for adding modules.

If you want to play with an already written application, grab the result of the tutorial instead, containing an Album module that performs CRUD over a database table. It's more functional and realistic than an Hello World.

The skeleton application is a good move, as it already includes a functional application and .htaccess, so you only need a bit of Apache configuration to get it up and running. Previously, code generation was the way to set up a Zend Framework 1 application for a newbie, and I can't say getting Zend_Tool and the zf binary to work was all that simple at the first try.

The noticeable change in the application structure is the module layout:

Application/
    config/
    src/
    views/

Each module separates production code (classes) from config and from view templates, while not forcing further divisions between controllers, models, services and other objects.

It also means that theoretically you could drop a module in an application as a single folder, along with others. But it doesn't mean that modules do not interact: for example the Two Step View layout specified by the Application module is also used by the other modules. This is done by merging the configurations of each module into a single one.

Standards

With a new major version, the framework can adopt modern standards that interrupt backward compatibility, like Symfony 2 did:

  • being PHP 5.3 only, classes are organized into namespaces and not only virtual packages separated by underscores.
  • PSR-0 autoloading is adopted in all modules src/ folder, so there is no mismatch between classes and file names.
  • no Interface suffix anymore for names.
  • marker interfaces for exceptions, so that PHP 5.3 exceptions are used by inheritance and exceptions are associated to a module by implementing an interface (e.g. Zend\Json\Interface).
  • no underscore prefix for private and protected properties and methods.

Nothing revolutionary, but it frees from some burdens while writing new code.

Not really lightweight

Configuration is a bit long-winded but scales well: for example, the 'di' key in a module's config file contains all classes along with their injection parameters. A full stack framework comes with accidental complexity, that we have to accept in order to borrow all its features.

Classes are considered equivalent to objects, but I'm sure there is some way to instance more than one object of the same class to inject, since I already see aliases available for controllers.

I would also try to limit this injection mechanism to the framework's classes, as it is a more flexible form of the same old configuration containing database credentials, drivers, paths and so on. I say more flexible as you can reconfigure the object graph instead of providing just a giant INI. For configuration of other layers, I would stick to my own mechanism (domain-related Factories and Builders), independent from external components.

Another point of boilerplate (necessary for performance, I think) is the Module.php configuration that act as a Facade for the module, defining autoloading. It is pretty standard code so it won't be a cause of pain.

Controllers can be very lightweight with respect to Zend Framework 1: they can specify setters for injection instead of grabbing around hunting for objects. It's not a magic feature: you specify their list in the configuration, and this would make you think about collaborators and their number. But the controller remains slim and even instantiable in isolation (in theory).

Actions return a view model so that they do not have to know the view object at all:

class AlbumController extends ActionController
{
    /**
     * @var \Album\Model\AlbumTable
     */
    protected $albumTable;

    public function indexAction()
    {
        return array(
            'albums' => $this->albumTable->fetchAll(),
        );
    }

    public function setAlbumTable(AlbumTable $albumTable)
    {
        $this->albumTable = $albumTable;
        return $this;
    }   
}

Similarities with 1.x

Some conventions and APIs are verbose as in Zend Framework 1, but that means you won't have to learn them again:

  • the controller's API and its helpers: from a controller you have access to the request, and to features mixed in such as redirecting.
  • Forms allow the definition of elements (with labels, validation, and filters) in subclasses providing init().
  • Views conform to the usual folder structure <controller>/<action>.phtml; helpers like escape() and url() are available along with view variables on $this.

Basic database support is also present with the Table Data Gateway classes and its derivatives. Of course you can integrate Doctrine2 or other ORMs of your choice.

Conclusions

The following question is the elePHPant in the room: Why should I use Zend Framework 2 instead of Symfony 2? This analysis provided a point: ZF2 has an easier upgrade path for the code of Zend Framework 1 applications and for the know-how you have acquired. Furthermore, it's not less modern than Symfony in its design choices despite being a port instead of a full rewrite.

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}