在Zend框架2,爲LazyServiceLoader環形依賴性被發現例如`UserService`
我有一個控制器類UserController
UserController
取決於UserService
UserService
取決於UserChangedListener
UserChangedListener
依賴於SomeOtherClass
SomeOtherClass
取決於UserService
所以在這裏我UserController
和SomeOtherClass
取決於UserService
。
我得到錯誤:
爲LazyServiceLoader循環依賴被發現的情況下
UserService
上述錯誤(即用於LazyServiceLoader循環依賴),當我在UserChangedListener
SomeOtherClass
發生
而且我有
「zendframework/zend-servicemanager」:「^ 2.7.5 ||^3.0.3" ,
UserControllerFactory.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);
}
}
UserServiceFactory.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)
);
}
}