2012-09-07 19 views
2

投下一些評論我現在正在使用Doctrine 2的東西,並落在Doctrine模塊上進行驗證,如ObjectExists.phpNoObjectExists.php從Doctrine 2模塊ObjectExists.php'ObjectExists.php'

我的問題是,從原來的代碼,可以發現here

/** 
    * Constructor 
    * 
    * @param array $options required keys are `object_repository`, which must be an instance of 
    * Doctrine\Common\Persistence\ObjectRepository, and `fields`, with either 
    * a string or an array of strings representing the fields to be matched by the validator. 
    * @throws \Zend\Validator\Exception\InvalidArgumentException 
    */ 
    public function __construct(array $options) 
    { 
     if (!isset($options['object_repository']) || !$options['object_repository'] instanceof ObjectRepository) { 
      if (!array_key_exists('object_repository', $options)) { 
       $provided = 'nothing'; 
      } else { 
       if (is_object($options['object_repository'])) { 
        $provided = get_class($options['object_repository']); 
       } else { 
        $provided = getType($options['object_repository']); 
       } 
      } 

      throw new Exception\InvalidArgumentException(sprintf(
       'Option "object_repository" is required and must be an instance of' 
        . ' Doctrine\Common\Persistence\ObjectRepository, %s given', 
       $provided 
      )); 
     } 

     $this->objectRepository = $options['object_repository']; 

     if (!isset($options['fields'])) { 
      throw new Exception\InvalidArgumentException(
       'Key `fields` must be provided and be a field or a list of fields to be used when searching for' 
        . ' existing instances' 
      ); 
     } 

     $this->fields = $options['fields']; 
     $this->validateFields(); 

     parent::__construct($options); 
    } 

我不能說這裏提到$options所需的密鑰是object_repository,這必須是Doctrine\Common\Persistence\ObjectRepository的實例」的事實

由於Doctrine\Common\Persistence\ObjectRepository是一個接口,應該怎麼解碼的發言?

或換句話說,我該如何叫這個ObjectsExists類的構造函數並通過object_repository,它必須是Doctrine\Common\Persistence\ObjectRepository的實例?

有人可以提出這個問題,我正在研究這個問題,所以不要苛刻我的問題。

感謝

回答

1

由於Doctrine\Common\Persistence\ObjectRepository是一個接口,你不能實例化,但你可以實現它。

class MyObjectRepository implements Doctrine\Common\Persistence\ObjectRepository 
{ 
    // ... 
} 

現在的MyObjectRepository每個實例都會遇到的ObjectsExistsobject_repository要求。

new ObjectsExists(array(
    'object_repository' => new MyObjectRepository(), 
    // ... 
)); 

進一步瞭解instanceof

instanceof被用於確定一個PHP變量是否是某個類的實例化的對象。

instanceof也可用於確定變量是否是從父類繼承的類的實例化對象。

instanceof也可用於確定變量是否是實現接口的類的實例化對象。

0

實現Doctrine \ Common \ Persistence \ ObjectRepository的最常見的類是Doctrine \ ORM \ EntityRepository。

所以,如果你正在使用Doctrine ORM的object_repository選項應該是喜歡你的UserRepository(顯式定義,或只是普通的一個,你從$em->getRepository('User')回來)

它沒有明確定義的原因因爲[No] ObjectExists驗證器不在DoctrineORMModule中,而只是DoctrineModule。因此,如果您使用ORM的而不是,則只需創建自己的實現ObjectRepository的UserRepository類。