Zend\ServiceManager is usually configured in two places: an array in a config file or a method within your Module class. In either case, you provide a nested array of configuration information.
For example, in a config file:
'service_manager' => array(
'invokables' => array(
'session' => 'ZendSessionStorageSessionStorage',
'factories' => array(
'db' => 'ZendDbAdapterAdapterServiceFactory',
Within the service_manager array, there are a set of nested arrays which are generally used to configure how you want a given class to be instantiated. the names of these sub-arrays are hardcoded, so you just need to learn their names and the difference between them:
A string which is the name of a class to be instantiated. The ServiceManager will instantiate the class for you when needed. For example:
An instance of a class. This is used to register already instantiated objects with the ServiceManager. For example:
A callback that will return an instantiated class. This is for cases where you need to configure the instance of the object. For example:
Another name for a class. Generally, you see this used within a module so that the module uses it's own alias name and then the user of the module can configure exactly which class that alias name is to be.
A callback that is executed every time the ServiceManager creates a new instance of a class. These are usually used to inject an object into the new class instance if that class implements a particular interface.
In this case, the initialiser checks if $instance implements AuthorizeAwareInterface and if it injects the Authorize service into the instance ready for use. Another really common use-case is injecting a database adapter and Zend Framework supplies ZendDbAdapterAdapterAwareInterface for this case.
There is also the abstract_factories key, but this is rarely used in most apps.
A factory instance that can create multiple services based on the name supplied to the factory. This is used to enable ServiceManager to fallback to another Service Locator system if it can cannot locate the required class from within its own configuration. As an example, you could write an abstract factory that proxies to Symfony's DependencyInjection component. Items within this sub-key can be either a classname string or an instance of the factory itself For example:
All abstract factories must implement ZendServiceManagerAbstractFactoryInterface.
Controllers, View helpers & Controller plugins
Note that the MVC system instantiates controllers, view helpers, form elements, input filters, controller plugins and others using specialised versions of ServiceManager. This means that the same keys that you use for service manager configuration are used for setting up view helpers and controller plugins, etc. – you just use a different top level configuration key and method name the in Module class:
|Manager||Key name in configuration array||Method name in Module.php|
This is reuse of knowledge at its best!