将ZF2迁移到ZF3:热转换“realServiceLocator”?

时间:2017-06-24 08:20:49

标签: zend-framework2 migration service-locator zend-framework3 zend-servicemanager

在我的Zend Framework 2应用程序的Factory类中,我经常使用这样的结构:

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

因此,为了访问“常用”服务,我首先检索了ServiceLocator。这种方法在Hydrator s,Controller和其他服务的工厂中是必要的,这些服务具有自己的ServiceManager s。因为对他们而言,输入ServiceLocatorAbstractPluginManager而不是Zend\ServiceManager\ServiceManager

现在我为我的工厂做了第一个迁移步骤并取代了一些常见的东西:

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

如何使$container->getServiceLocator()适应ZF3?

1 个答案:

答案 0 :(得分:3)

不推荐使用

getServiceLocator(),因此您无法在ZF3中使用此版本。您可以使用Interop\Container\ContainerInterface实例使服务管理器可用,同时使工厂成为以下

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