In the Factory
classes of my Zend Framework 2 application, I often used such a construction:
// The signature was actually wrong, since it was always the `AbstractPluginManager` (or the `Zend\ServiceManager\ServiceManager` for the "common" services) and not just `ServiceLocator`, and it also was used as `AbstractPluginManager` (or `ServiceManager` for the "common" services). The `ServiceLocatorInterface` did not provide the `getServiceLocator()` method.
public function createService(ServiceLocatorInterface $serviceLocator)
{
// the common ServiceLocator
$realServiceLocator = $serviceLocator->getServiceLocator();
$myServiceFoo = $realServiceLocator->get('My\Service\Foo');
$myServiceBar = new \My\Service\Bar($myServiceFoo);
...
}
So to access a "common" service, I first retrieved the ServiceLocator
. This approach was necessary in factories for Hydrator
s, Controller
s, and other services, that have their own ServiceManager
s. Because for them the input ServiceLocator
was AbstractPluginManager
and not the Zend\ServiceManager\ServiceManager
.
Now I made the first migration step for my factories and replaced some common things:
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
// the common ServiceLocator
$realServiceLocator = $container->getServiceLocator();
$myServiceFoo = $realServiceLocator->get('My\Service\Foo');
$myServiceBar = new \My\Service\Bar($myServiceFoo);
...
}
How to adapt the $container->getServiceLocator()
to the ZF3?
getServiceLocator()
is deprecated so you can not use this one in ZF3. You would be able to make the service manager available using an instance ofInterop\Container\ContainerInterface
while making factories as the following