Accessing the ServiceManager from the ViewHelperManager in ZF2

Reading Time: < 1 minutes

Sometimes the new ServiceManager(s) in Zend Framework 2 are a bit confusing. We don’t have one, we have several instances.

So recently I was writing a factory for a ViewHelper and wanted to access the application configuration from there. As usual, I was attempting it like this

[code lang=”php”]
/**
* @param ServiceLocatorInterface $serviceLocator
* @return MyConfiguration
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
$instance = new MyConfiguration();
$configuration = $serviceLocator->get(‘configuration’);

// haha – nope!

if(!empty($configuration[‘whatever’])) {
$instance->setConfiguration($configuration[‘whatever’]);
}

return $instance;
}[/code]

It ended up throwing an exception, saying the configuration could not be found. To make it short, after some searching I found this one

[code lang=”php”]$serviceManager = $serviceLocator->getServiceLocator();[/code]

Intuitive, isn’t it? But it seems to work, so the factory looks like this now:

[code lang=”php”]
/**
* @param ServiceLocatorInterface $serviceLocator
* @return MyConfiguration
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
$serviceManager = $serviceLocator->getServiceLocator();
$instance = new MyConfiguration();
$configuration = $serviceManager->get(‘configuration’);

if(!empty($configuration[‘whatever’])) {
$instance->setConfiguration($configuration[‘whatever’]);
}

return $instance;
}[/code]

Leave a Reply

Your email address will not be published.

I accept the Privacy Policy

This site uses Akismet to reduce spam. Learn how your comment data is processed.