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;                    
                },
            )
        );
    }

    ...
}

I'm available for contracting work. Check out my LinkedIn profile and my portfolio page for an overview of my skills and experience. If you are interested in working with me please use the contact form to get in touch.

ZF2 Service Manager Aware Objects

Leave a Reply

Your email address will not be published. Required fields are marked *