3

ZF2 フォームの検証では、カスタム バリデーターにエンティティ マネージャーが必要です。Zend\ServiceManager\ServiceLocatorAwareInterface を使用してバリデータでサービス ロケータを取得し、そこからエンティティ マネージャを取得できるようにします。

私の問題は、この Zend\ServiceManager\ServiceLocatorAwareInterface::setServiceLocator が目的の ServiceLocator ではなく、「Zend\Validator\ValidatorPluginManager」を挿入することです。

この問題を解決する方法を知っている人はいますか?

私の抽象コントローラー

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" 
4

2 に答える 2

3

この理由は、バリデーターにZend\Validator\ValidatorPluginManager注入されているためです。getServiceLocatorで Service Manager コールが必要な場合Zend\Validator\ValidatorPluginManager

たとえば、次の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

    }
}

お役に立てれば :)

ストヤン

于 2013-04-11T15:00:49.910 に答える