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

:

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:

config/autoload/global.php:

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:

module/Application/src/Application/ConfigAwareInterface.php:

We can now add this to a controller:

module/Application/src/Application/Controller/IndexController.php:

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:

module/Application/Module.php:

(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:

module/Application/Module.php:

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.