Accessing the ServiceManager from the ViewHelperManager in ZF2

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

    /**
     * @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;
    }

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

$serviceManager = $serviceLocator->getServiceLocator();

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

     /**
     * @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;
    }

Leave a Reply

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