Over a million developers have joined DZone.

Injecting Dependencies Into Your ZF2 Controllers

DZone's Guide to

Injecting Dependencies Into Your ZF2 Controllers

· DevOps Zone
Free Resource

The Nexus Suite is uniquely architected for a DevOps native world and creates value early in the development pipeline, provides precise contextual controls at every phase, and accelerates DevOps innovation with automation you can trust. Read how in this ebook.

When starting working with Zend Framework 2, it’s common to copy the skeleton and put your controller definitions in module.config.php like this:

'controllers' => array(
  'invokables' => array(
    'Application\Controller\Index' => 'Application\Controller\IndexController',
    'Application\Controller\Blog' => 'Application\Controller\BlogController',

The controllers keyword is picked up by the ControllerManager which is an instance of the ServiceManager which means that it creates the controller instance for you when the dispatcher needs it.

As it’s just a service manager, we configure it to inject the dependencies that the controller needs rather than having to go fishing for them later. The easiest way to do this is to add a callback to the Module class to do the work in.

To convert the Blog controller, we would remove the line from the invokables config array and then write a getControllerConfig() method that would looks something like this:

public function getControllerConfig()
  return array(
    'factories' => array(
      'Application\Controller\Blog' => function ($sm) {
          $locator = $sm->getServiceLocator();
          $blogMapper = $locator->get('Application\Mapper\BlogMapper');
          $commentMapper = $locator->get('Application\Mapper\CommentMapper');

          $controller = new BlogController($blogMapper, $commentMapper);
          return $controller;

ZF2 controllers tend to extend AbstractActionController which does not define a constructor. This means that you can define your own constructor in your controllers and use it to inject the dependencies that your controller needs. In this example, our BlogController needs two database mappers, so we retrieve them from the service manager and then instantiate our BlogController object.

Nice and simple.

The DevOps Zone is brought to you in partnership with Sonatype Nexus.  See how the Nexus platform infuses precise open source component intelligence into the DevOps pipeline early, everywhere, and at scale. Read how in this ebook


Published at DZone with permission of Rob Allen, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}