Over a million developers have joined DZone.

Injecting Dependencies Into Your ZF2 Controllers

· DevOps Zone

The DevOps zone is brought to you in partnership with Sonatype Nexus. The Nexus suite helps scale your DevOps delivery with continuous component intelligence integrated into development tools, including Eclipse, IntelliJ, Jenkins, Bamboo, SonarQube and more. Schedule a demo today

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. Use the Nexus Suite to automate your software supply chain and ensure you're using the highest quality open source components at every step of the development lifecycle. Get Nexus today

Topics:

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

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}