2016-10-21 1 views
6

ArrayCollectionEmail 엔티티가 이미 있는지 확인해야하지만 전자 메일을 문자열로 확인해야합니다 (엔티티에는 ID가 포함되어 있고 다른 엔트리와의 관계가 있습니다. 이런 이유로 나는 모든 전자 우편을 영속하는 분리되는 테이블을 이용한다).Doctrine의 ArrayCollection :: exists 메소드 사용 방법

자, 먼저이 코드 작성에 :

/** 
    * A new Email is adding: check if it already exists. 
    * 
    * In a normal scenario we should use $this->emails->contains(). 
    * But it is possible the email comes from the setPrimaryEmail method. 
    * In this case, the object is created from scratch and so it is possible it contains a string email that is 
    * already present but that is not recognizable as the Email object that contains it is created from scratch. 
    * 
    * So we hav to compare Email by Email the string value to check if it already exists: if it exists, then we use 
    * the already present Email object, instead we can persist the new one securely. 
    * 
    * @var Email $existentEmail 
    */ 
    foreach ($this->emails as $existentEmail) { 
     if ($existentEmail->getEmail()->getEmail() === $email->getEmail()) { 
      // If the two email compared as strings are equals, set the passed email as the already existent one. 
      $email = $existentEmail; 
     } 
    } 

그러나 내가했던 것과 같은 일을 더 elgant 방법이 될 것으로 보인다 방법 exists을 본 ArrayCollection 클래스를 읽는.

그러나 나는 그것을 사용하는 방법을 모르겠다 : 누군가가 위의 코드 주어진이 메서드를 사용하는 방법을 설명 할 수 있습니까?

답변

8

물론 PHP에서는 Closure이 단순한 Anonymous functions입니다. 당신은 다음과 같이 코드를 다시 작성할 수 :

$exists = $this->emails->exists(function($key, $element) use ($email){ 
     return $email->getEmail() === $element->getEmail()->getEmail(); 
     } 
    ); 

희망이 도움

1

당신이 @Matteo 감사합니다!

public function addEmail(Email $email) 
{ 
    $predictate = function($key, $element) use ($email) { 
     /** @var Email $element If the two email compared as strings are equals, return true. */ 
     return $element->getEmail()->getEmail() === $email->getEmail(); 
    }; 

    // Create a new Email object and add it to the collection 
    if (false === $this->emails->exists($predictate)) { 
     $this->emails->add($email); 
    } 

    // Anyway set the email for this store 
    $email->setForStore($this); 

    return $this; 
} 
+1

하이 @Aerendir 좋은 직장 : 그냥 완전성에 대해

이 내가 와서있는 코드입니다! – Matteo