Initialising the Service Manager in Zend Framework 2

You may have a need for initialising the Service Manager in Zend Framework 2 as a separate instance to the included framework service manager.

Similarly, if you’ve decided to use the Zend\ServiceManager module for your project, you’ll need to instantiate it in the following way:

Get the service manager configuration. In this case I’m getting it from the ZF2 application.config.php file:

$configuration = require realpath(__DIR__ . '/path/to/application') . '/config/application.config.php’;
$smConfig = isset($configuration['service_manager']) ? $configuration['service_manager'] : [];
$serviceManager = new ServiceManager(new ServiceManagerConfig($smConfig));

If you’re doing this inside a ZF project, you’ll need to set the application config

$serviceManager->setService('ApplicationConfig', $configuration);

Depending which version of the Zend\ServiceManager you have available, you may find that certain parts of the service manager don’t get set with the code above. This can include delegators, initializers and abstract factories. If you find this is the case, loading the module manager will fire off the listener that merges this extra config with your standards service manager config:


Leave a Reply

Your email address will not be published. Required fields are marked *