在我的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。因为对他们而言,输入ServiceLocator
是AbstractPluginManager
而不是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?
答案 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);
...
}