Injecting ZF2 Service Manager into Doctrine Entities

Making ZF2 services available within Doctrine entities is not as trivial as with objects that are created via the ZF2 factory methods. The problem is that Doctrine Entities are not generated via regular ZF2 factory methods but by the Doctrine Entity Manager. Nevertheless it’s possible to inject dependencies into Doctrine entities.

Doctrine’s event manager offers a postLoad event which is called after the entity has been loaded. We can add a new listener to this event during our regular bootstrapping process.
Continue reading “Injecting ZF2 Service Manager into Doctrine Entities”

Injecting ZF2 Service Manager into Doctrine Entities

ZF2 Flash Messages

A consistent message and notification implementation is one of the key building stones of modern web apps. ZF2 makes it very easy to implement this with the FlashMessenger controller plugin.

To integrate the flash messenger into your web app you need to follow 3 simple steps.

First, register the FlashMessengers messages as a view variable in your Module.php. The FlashMessenger supports namespaces which is very useful for having different styling for different message contexts. This example uses 3 different namespaces. You are free to implement as many as you want. I’m merging the default namespace with the info namespace which lets you assign general messages without the need to specify a namespace.

public function onBootstrap(MvcEvent $e)
{
    $eventManager = $e->getApplication()->getEventManager();
    $moduleRouteListener = new ModuleRouteListener();
    $moduleRouteListener->attach($eventManager);

    // Show flashmessages in the view
    $eventManager->attach(MvcEvent::EVENT_RENDER, function($e) {
        $flashMessenger = new FlashMessenger;

        $messages = array();

        $flashMessenger->setNamespace('success');
        if ($flashMessenger->hasMessages()) {
            $messages['success'] = $flashMessenger->getMessages();
        }
        $flashMessenger->clearMessages();

        $flashMessenger->setNamespace('info');
        if ($flashMessenger->hasMessages()) {
            $messages['info'] = $flashMessenger->getMessages();
        }
        $flashMessenger->clearMessages();

        $flashMessenger->setNamespace('default');
        if ($flashMessenger->hasMessages()) {
            if (isset($messages['info'])) {
                $messages['info'] = array_merge($messages['info'], $flashMessenger->getMessages());
            }
            else {
                $messages['info'] = $flashMessenger->getMessages();
            }
        }
        $flashMessenger->clearMessages();

        $flashMessenger->setNamespace('error');
        if ($flashMessenger->hasMessages()) {
            $messages['error'] = $flashMessenger->getMessages();
        }
        $flashMessenger->clearMessages();

        $e->getViewModel()->setVariable('flashMessages', $messages);
    });
}

To have the messages display consistently throughout your application it is best to add the message HTML to the layout template (in most cases module/Application/view/layout/layout.phtml).

<?php
  if ($this->flashMessages) {
    foreach ($this->flashMessages as $context => $messages) {
      echo '<div class="message-container ' . $context . '"><ul>';
      foreach ($messages as $message) {
        echo '<li>' . $message . '</li>';
      }
      echo '</ul></div>';
    }
  }
?>

Finally you can assign messages in your controller. You don’t need to specify a namespace if you want to assign messages to the info group.

$flashMessenger = $this->flashMessenger();
$flashMessenger->setNamespace('success');
$flashMessenger->addMessage('Foo!');
ZF2 Flash Messages

ZF2 Service Manager Aware Objects

In one of my previous posts I explained how to set up Dependency Injection in Zend Framework 2. Even though this approach is highly flexible it doesn’t always fit your project needs. Sometimes it is more suitable to fetch object instances from the service manager directly within the object. This post will explain how to implement this.

ZF2 automatically calls the setServiceManager method for objects implementing the ServiceManagerAwareInterface interface when instanciating these objects via the service manager. To set this up 2 steps are necessary:

  1. The class which needs to have access to the service manager needs to implement ServiceManagerAwareInterface
  2. The service manager needs to have the factory methods for the object that consumes the service manager and for the objects which are to be instanciated by the service manager

To implement the ServiceManagerAwareInterface the class needs to simply have a setServiceManager method which takes a ServiceManager object as an argument. This class needs to populate a property which gives other functions access to the service manager.

module/User/src/User/Model/User.php

<?php
namespace User\Model;

use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;

abstract class User implements ServiceManagerAwareInterface {
    protected $serviceManager;

    /*
     * Populate service manager property
     */
    public function setServiceManager(ServiceManager $serviceManager)
    {
        $this->serviceManager = $serviceManager;
    }

    /*
     * Do some foo
     */
    protected function foo()
    {
        $foo = $this->serviceManager->get('Foo');
        $foo->bar();
    }
}

Now when creating instances of objects which implement the ServiceManagerAwareInterface using service manager factory methods, the service manager will be automatically made available.

module/User/Module.php

<?php
namespace User;

class Module
{
    ...

    public function getServiceConfig()
    {
        return array(
            'factories' => array(
                'User' => function($sm)
                {
                    $user = new Model\User();
                    return $user;
                },
                'Foo' => function($sm)
                {
                    $foo = new \Foo();
                    return $foo;                    
                },
            )
        );
    }

    ...
}
ZF2 Service Manager Aware Objects

ZF2 Dependency Injection

Now that Zend Framework 2 (ZF2) has been released for more than 6 months and most of the early issues have been fixed I decided to switch from ZF1 to ZF2 for my latest project.

ZF2’s MVC layer has been completely rewritten and is now event driven. ZF2 also adds functionality to handle dependency injection (DI) allowing for a more modular structure by removing hard coded dependencies. All those new changes represent a bit of a learning curve for anyone getting started with ZF2. If DI is new to you the Zend DI Quickstart is a good place to familiarize yourself with the concept.

This post will explain how to set up dependency injection on top of the ZF2 Skeleton Application.

In this simple example we will assume that the User controller depends on having an instance of the User object. Further the User object needs to consume an instance of Zend\Log\Logger. In the first step we simply need to set up the constructors of class User and class UserController to take the Logger object instance and the User object instance as arguments and assign the objects to a class property.

module/User/src/User/Model/User.php

<?php

namespace User\Model;

use Zend\Log\Logger;

class User {
    protected $logger;

    public function __construct(Logger $logger)
    {
        $this->logger = $logger;
    }

    ...
}

module/User/src/User/Controller/UserController.php

<?php
namespace User\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

use User\Model\User;

class UserController extends AbstractActionController {
    protected $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

    ...
}

Next we need to set up the controller config and the service manager config for DI. To retrieve objects from the service manager the factory pattern is implemented. The individual factory configuration sections are closures which instantiate, configure and return the requested objects. As you can see the objects we defined as dependencies in the first step are fetched from the service manager and passed to the constructors when instantiating the objects.

module/User/Module.php

<?php
namespace User;

class Module
{
    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

    public function getAutoloaderConfig()
    {
        ...
    }

    public function getServiceConfig()
    {
        return array(
            'factories' => array(
                'User' => function($sm)
                {
                    $logger = $sm->get('Logger');
                    $user = new Model\User($logger);
                    return $user;
                },
                'Logger' => function($sm)
                {
                    $config = $sm->get('config');
                    $logger = new \Zend\Log\Logger;
                    $writer = new \Zend\Log\Writer\Stream($config['log']['file']);
                    $logger->addWriter($writer);

                    return $logger;
                },
            )
        );
    }

    public function getControllerConfig()
    {
        return array('factories' => array(
            'User\Controller\User' => function($cm)
            {
                $sm = $cm->getServiceLocator();
                $user = $sm->get('User');
                $controller = new Controller\UserController($user);
                return $controller;
            }
        ));
    }
}

A better place to place the Logger object factory configuration is in the Module.php of the Application module. In this example it is placed in the Module.php of the User module for illustration purposes.

If you read the Zend Framework 2 tutorial you probably configured your User controller as an invokable in your module.config.php. If this is the case you need to remove this section, otherwise the service manager is not used to instantiate the UserController object and dependency injection won’t work.
module/User/config/module.config.php

'controllers' => array(
    'invokables' => array( // REMOVE ME!!!
        'User\Controller\User' => 'User\Controller\UserController'
    ),
    ...
ZF2 Dependency Injection