Key Takeaways
- Zend Framework 2 (ZF2) offers four different ways to obtain the software, including direct download, GitHub repository, Composer, and PEAR2_Pyrus.
- The new autoloading system in ZF2 provides three different options, removing the need for the heavy use of ‘require_once’ lines that were common in the first version.
- ZF2 has been developed following the Inversion of Control (IoC) to ensure code is as decoupled as possible, making it more flexible and maintainable.
- The new Event Manager in ZF2 makes the framework event-driven, allowing developers to manage a set of events to change the application flow as needed.
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 yourcomposer.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#StandardFor 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 therequire_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/ProjectHowever, 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 classZendServiceManager
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
Frequently Asked Questions (FAQs) about Zend Framework 2
What are the new features in Zend Framework 2?
Zend Framework 2 introduces several new features and improvements over its predecessor. It includes a new MVC layer, which is significantly different from the Zend Framework 1 MVC. The new MVC layer includes features such as event-driven architecture and a module system that makes the application more flexible and easier to maintain. It also includes a new service manager component that helps manage the creation of objects and inject dependencies, making the code more testable. Additionally, Zend Framework 2 is built with PHP 5.3 and utilizes namespaces and closures.
How does Zend Framework 2 compare to other PHP frameworks?
Zend Framework 2 is a robust and feature-rich framework that offers a high degree of flexibility and scalability. It is built with best practices in mind and includes components for many common tasks in web development. Compared to other PHP frameworks, Zend Framework 2 stands out with its modular architecture, which allows developers to use only the components they need, reducing the application’s complexity and improving performance. It also has a large and active community, providing a wealth of resources and support.
Is Zend Framework 2 suitable for beginners?
While Zend Framework 2 is a powerful tool, it has a steep learning curve and may not be the best choice for beginners. It requires a good understanding of object-oriented programming and design patterns. However, for those willing to invest the time to learn, it can be a highly rewarding framework that offers a great deal of flexibility and control.
How does the module system work in Zend Framework 2?
The module system in Zend Framework 2 is one of its most powerful features. It allows developers to organize their code into reusable modules, which can be easily shared across different applications. Each module is self-contained and can have its own configuration, view scripts, and even its own MVC layer. This makes the code more maintainable and easier to test.
What is the role of the Service Manager in Zend Framework 2?
The Service Manager is a key component in Zend Framework 2. It is responsible for creating and managing objects, and injecting dependencies. This makes the code more testable and easier to maintain. The Service Manager also supports lazy loading, which means that objects are only created when they are needed, improving the application’s performance.
How does Zend Framework 2 handle database operations?
Zend Framework 2 provides a powerful and flexible way to work with databases. It includes an SQL abstraction layer and an object-relational mapping (ORM) tool. The SQL abstraction layer allows developers to write database queries in a database-agnostic way, while the ORM tool makes it easy to map database tables to PHP objects.
How does Zend Framework 2 support testing?
Zend Framework 2 is built with testing in mind. It includes a PHPUnit testing framework and provides support for test-driven development (TDD). The modular architecture and the Service Manager also make the code easier to test, as each module can be tested independently and mock objects can be easily created.
How does Zend Framework 2 handle security?
Security is a key concern in Zend Framework 2. It includes several components to help secure your application, such as input filtering and validation, cryptography tools, and protection against common web attacks like cross-site scripting (XSS) and cross-site request forgery (CSRF).
What is the future of Zend Framework 2?
Zend Framework 2 continues to be a popular choice among PHP developers. However, it’s worth noting that it has been succeeded by Laminas Project, which is the official successor to Zend Framework. Laminas Project continues the development and support of the framework under an open-source model.
How can I start learning Zend Framework 2?
There are many resources available to learn Zend Framework 2. The official documentation is a good starting point. There are also many tutorials, books, and online courses available. It’s also helpful to join the community and participate in forums and discussion groups.
I'm a (full-stack) web and app developer with more than 5 years' experience programming for the web using HTML, CSS, Sass, JavaScript, and PHP. I'm an expert of JavaScript and HTML5 APIs but my interests include web security, accessibility, performance, and SEO. I'm also a regular writer for several networks, speaker, and author of the books jQuery in Action, third edition and Instant jQuery Selectors.