Get started to zf2 and why to switch from zf1

  • ZF1 way: Singletons, registers, soft and hard dependencies
  • ZF2 way: Even-Driven Services flexibility, better secure defaults, contexts of escaping, dependencies injection (inversion of control).

Instead of using hard dependencies and dificult to test code:

public function someAction(){  $front = Zend_Controller_Front::getInstance();  $bootstrap = $front->getParam('bootstrap');  $db = $bootstrap->getResource('db');  $service = new SomeService($db);  $this->view->results = $service->doSomething();}


With ZF2 you can achieve this:

public function setService($service){  $this->service = $service;}public function someAction(){  return array(    'results' => $this->service->doSomething();  ); }

You need to use Dependency Injection when getting the controller:

function ($controllers){  $services = $controllers->getServiceLocator();  $service = $services->get('SomeService');  $controller = new SomeController();  $controller->setService($service);  return $controller;}


  • Easy replacements which means easier to test
  • Code for construcion is located in one place, easy reviewed place.
  • You can do things for separate services more easily



No discovery, you code injections. Explicit writing means less debuging

//Explicit services
array(‘services’, array(
  ‘foo’=>new SomeComponentFoo,
//Instantiable class
array(‘invokables’, array(
//Callable that returns and object
array(‘factories’, array(
    return new SomeComponentFoo(
//Callable that handles multiple services
array(‘abstract_factories’, array(
//Example of abstract factory
class SampleAbstractFactory implements AbstractFactoryInterface {
  public funtion canCreateServiceWithName(
   ServiceLocatorInterface $services, $name, $requestedName
  ) { /* code.. */ }
  public funtion createServiceWithName  /* code.. */

//(un)Share a service
array(‘shared’, array(
  ‘EventManager’=>false, //default is true
//Operations on new instances, for example to automate injections like this
array(‘initializers’, array(
  function($instance, $services) {
    if($instance instanceof EventManagerAwareInterface) {
//Plugin example. $heplers is view helper plugin manager instance
array(‘factories’, array(
  ‘something’=> function($helpers) {
    $services = $helpers->getServiceLocator();
    $model = $services->get(‘SomeModel’);
    $helper = new SomethingHelper($model);
    return $helper;

Event Manager

Listen and react to trigger events in simple way

$events = new EventManager();
$events->attach(‘do’, function($e){
  $event = $e->getName();
  $params= $e->getParams();
  printf(‘Handled event %s with parameters %s, 
  $event, json_enccode($params));
$params=array(‘foo’ => ‘bar’, ‘baz’ => ‘bat’);
$events->trigger(‘do, null, $params);

Listen and react to trigger events to a group of objects or objects that don’t exist yet.

$shared = $events->getSharedEventManager();
$shared =  $services->get(‘SharedEventManager’);

$shared->attach(‘ZendStdlibDispatchableInterface’, ‘dispatch’, $callback, $priority);

Everything is an event

Boostrap listeners run modules, route listeners run modules, dispatch listeners run modules.

Controllers are services

Use ServiceManager to wire default workflow and event listeners.

Plug and play modules

They should do one thing and do it well. They provide services for MVC and wire event listeners.

 Modules are implemented as a namespace with a single Module.php class file.



Module example

Edit module/MyMarkdown/Module.php

namespace  MyMarkdown;

use ZendViewHelperAbstractHelper;

class Module extends AbstractHelper
  public function getViewHelperConfig(){
    return array(‘services’, array(‘markdown’ => $this));
  public function __invoke($string = null){
    require_once ‘php-markdown/markdown.php’;
    return Markdown($string);

Add the MyMarkdown module to application in config/application.config.php

return array(
  ‘modules’ => array(
  /* … */

Test it in view script

<?= $this->markdown($this->someMarkdowntext) ?> 

What you can do if the module you want exist? Use ‘git submodule add’, add module name to your config/application.config.php file and you are done.


Controller example

They are very similar than in ZF1. In ZF2 you return something.

namespace ApplicationController;

use ZendMvcControllerAbstractActionController;
use ZendViewModelViewModel;

class IndexController extends AbstractActionController
  public function indexAction()
    return new ViewModel();


Key points to remember for using ZF2

  • Know to configure services.
  • Know to wire event listeners.
  • Controllers return informa
    tion as they are now services.
  • Modules inform the MVC of services (controllers!) and wire events.



Etiquetes: , ,

Deixa un comentari

Fill in your details below or click an icon to log in: Logo

Esteu comentant fent servir el compte Log Out /  Canvia )

Google+ photo

Esteu comentant fent servir el compte Google+. Log Out /  Canvia )

Twitter picture

Esteu comentant fent servir el compte Twitter. Log Out /  Canvia )

Facebook photo

Esteu comentant fent servir el compte Facebook. Log Out /  Canvia )


S'està connectant a %s

%d bloggers like this: