Injecting dependencies into your ZF2 controllers – Rob Allen's DevNotes


: 3

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:

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:

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.