对于我的 ZF2 表单验证,我需要自定义验证器中的实体管理器。我 Zend\ServiceManager\ServiceLocatorAwareInterface 在我的验证器中获取服务定位器,这样我就可以从那里获取实体管理器。
我的问题是这个 Zend\ServiceManager\ServiceLocatorAwareInterface::setServiceLocator 注入(inject)了“Zend\Validator\ValidatorPluginManager”而不是所需的 ServiceLocator。
有人知道如何解决这个问题吗?
我的抽象 Controller
abstract class AbstractController extends AbstractActionController
{
/**
* This property contains the doctrine entitymanager.
* @var Doctrine\ORM\EntityManager
*/
protected $_entityManager;
/**
* This method returns the doctrine entitymanager.
* @return \Doctrine\ORM\EntityManager
*/
public function getEntityManager()
{
var_dump(spl_object_hash($this->getServiceLocator())); echo '<br>';
if (null === $this->_entityManager)
$this->_entityManager = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
return $this->_entityManager;
}
}
我的验证器:
class EntityUnique extends AbstractValidator implements ServiceLocatorAwareInterface
{
protected $_serviceLocator;
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
var_dump(spl_object_hash($serviceLocator)); echo '<br>';
$this->_serviceLocator = $serviceLocator;
}
function getServiceLocator()
{
return $this->_serviceLocator;
}
}
执行此操作时,两个 var_dumps 都会产生另一个对象哈希:
string(32) "000000005e4258390000000024a7f829"
string(32) "000000005e425a2d0000000024a7f829"
最佳答案
这是因为在您的验证器中,您正在注入(inject) Zend\Validator\ValidatorPluginManager
。如果您希望服务管理器调用 Zend\Validator\ValidatorPluginManager
上的 getServiceLocator
。
例如,查看下面的 someMethod()
方法:
class EntityUnique extends AbstractValidator implements ServiceLocatorAwareInterface
{
protected $_serviceLocator;
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
var_dump(spl_object_hash($serviceLocator)); echo '<br>';
$this->_serviceLocator = $serviceLocator;
}
public function getServiceLocator()
{
return $this->_serviceLocator;
}
public function someMethod()
{
$validatorPluginManager = $this->getServiceLocator();
$serviceLocator = $validatorPluginManager->getServiceLocator(); // HERE
}
}
希望这有帮助:)
斯托扬
关于php - ZF2 ServiceLocatorAwareInterface getServiceLocator 给我 Zend\Validator\ValidatorPluginManager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15951627/