在 Zend Framework 2 中,
我有一个控制器类UserController
UserController
取决于UserService
UserService
取决于UserChangedListener
UserChangedListener
取决于SomeOtherClass
SomeOtherClass
取决于UserService
所以在这里我UserController
和SomeOtherClass
都依赖于UserService
.
我收到错误:
例如,发现了 LazyServiceLoader 的循环依赖项
UserService
上述错误(即 LazyServiceLoader 的循环依赖)在我注入时SomeOtherClass
发生UserChangedListener
我有
"zendframework/zend-servicemanager": "^2.7.5 || ^3.0.3",
用户控制器工厂.php
class UserControllerFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$container = $container->getServiceLocator();
return new UserController(
$container->get(UserService::class)
);
}
public function createService(ServiceLocatorInterface $serviceLocator)
{
return $this($serviceLocator, UserController::class);
}
}
用户服务工厂.php
class UserServiceFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$service = new UserService(
$container->get(UserRepository::class)
);
$eventManager = $service->getEventManager();
$eventManager->attach($container->get(UserChangedListener::class));
return $service;
}
public function createService(ServiceLocatorInterface $serviceLocator)
{
return $this($serviceLocator, UserService::class);
}
}
UserChangedListenerFactory.php
class UserChangedListenerFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$container = $container->getServiceLocator();
return new UserChangedListener(
$container->get(SomeOtherClass::class)
);
}
public function createService(ServiceLocatorInterface $serviceLocator)
{
return $this($serviceLocator, UserChangedListener::class);
}
}
SomeOtherClassFactory.php
class SomeOtherClassFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
$rootLocator = $serviceLocator->getServiceLocator();
return new SomeOtherClass(
$rootLocator->get(UserService::class)
);
}
}