简体   繁体   中英

Migrating ZF2 to ZF3: Hot to convert the “realServiceLocator”?

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 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);
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM