Migrating ZF2 to ZF3: Hot to convert the "realServiceLocator"?

356 views Asked by At

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 Hydrators, Controllers, and other services, that have their own ServiceManagers. 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?

1

There are 1 answers

0
unclexo On

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 of Interop\Container\ContainerInterface while making factories as the following

public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
    $myServiceFoo = $container->get('My\Service\Foo');
    $myServiceBar = new \My\Service\Bar($myServiceFoo);
    ...
}