2016-10-21 8 views
6

Emailエンティティが既にArrayCollectionに存在するかどうかをチェックする必要がありますが、電子メールのチェックを文字列として実行する必要があります(Entityには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

関連する問題