---
title: Accessing the ServiceManager from the ViewHelperManager in ZF2
canonical: "https://windler.dev/blog/accessing-the-servicemanager-from-the-viewhelpermanager-in-zf2/"
pubDate: "2013-10-22T00:00:00.000Z"
description: How to access application configuration from a Zend Framework 2 ViewHelper factory by reaching the ServiceManager through the ViewHelperManager.
---

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

```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; }
```

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

```php
$serviceManager = $serviceLocator->getServiceLocator();
```

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

```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; }
```
