Injecting configuration into a ZF2 controller – Rob Allen's DevNotes


: 8

One thing you may find yourself needing to do is access configuration information in a controller or service class.

The easiest way to do this is to use the ServiceManger's initialiser feature. This allows you to write one piece of injection code that can be applied to multiple objects. It's easier to show this in action!

Let's assume that we have this configuration file:


That is, we have a key called 'application' that contains application-specific configuration that we would like to access in our controllers (or service classes).

Firstly we define a interface, ConfigAwareInterface:


We can now add this to a controller:


In the controller, we add a use statement, implement our interface and the required setConfig() method.

Finally, we add an initializer to the Module class:


(We also have a use ApplicationConfigAwareInterface; statement at the top!)

As getControllerConfig() is used by a specific ServiceManager only for controllers, we need to retrieve the main ServiceManager using getServiceLocator() in order to collect the merged configuration. As we only want the settings from within the 'application' key, we only pass that into the controller's setConfig() method.

The configuration settings are now available to us in any controller that implements ConfigAwareInterface.

We can also do this for service classes – we simply add another initalizer to the Module:


It also follows that you can use initializers for any type of generic injection, such as mappers, db adapters, loggers, etc. Simply create an interface and write an initalizer.