我有一个通过工厂实例化的类a和类B扩展类a的问题。
下面是一些示例代码:class ClassAFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
$one= $serviceLocator->get('doctrine.entitymanager.one');
$two= $serviceLocator->get('doctrine.entitymanager.two');
$three= $serviceLocator->get('Application'Service'three');
return new ClassA($one, $two, $three);
}
}
class ClassA implements ServiceLocatorAwareInterface
{
use ServiceLocatorAwareTrait;
private $one;
private $two;
private $three;
public function __construct(ObjectManager $one, ObjectManager $two, Three $three)
{
$this->one= $one;
$this->two= $two;
$this->three= $three;
}
}
class ClassB extends ClassA
{
// Some usefull code
}
我如何调用类B而不传递依赖关系,我如何检索由工厂完成的类A的实例:div ?
你不能直接这么做。也可以为ClassB
创建服务工厂,但这涉及到代码复制:
class ClassBFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
$one = $serviceLocator->get('doctrine.entitymanager.one');
$two = $serviceLocator->get('doctrine.entitymanager.two');
$three = $serviceLocator->get('Application'Service'three');
return new ClassB($one, $two, $three);
}
}
但是,您的类ClassA
(因此ClassB
)已经是服务定位器感知的,因此您可以惰性加载您的实体管理器;这样,你就根本不需要服务工厂了:
class ClassA implements ServiceLocatorAwareInterface
{
use ServiceLocatorAwareTrait;
private $one;
private $two;
private $three;
private function getOne()
{
if (!$this->one) {
$this->one = $this->getServiceLocator()
->get('doctrine.entitymanager.one');
}
return $this->one;
}
private function getTwo()
{
if (!$this->two) {
$this->two = $this->getServiceLocator()
->get('doctrine.entitymanager.two');
}
return $this->two;
}
public function __construct(Three $three)
{
$this->three = $three;
}
}
class ClassB extends ClassA
{
// Some usefull code
}
只需更新您的代码在ClassA
访问您的实体管理器与$this->getOne()
&$this->getTwo()
代替$this->one
&$this->two
.
之后,您可以访问ClassA
&ClassB
和其他人一样:
$a = $serviceLocator->get('Namespace'...'ClassA');
$b = $serviceLocator->get('Namespace'...'ClassB');