0

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

// 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. 这种方法在Hydrators、Controllers 和其他服务的工厂中是必要的,它们有自己的ServiceManagers。因为对他们来说,输入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?

4

1 回答 1

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);
    ...
}
于 2017-06-24T12:31:42.903 回答