2016-10-21 6 views
6

Мне нужно проверить, существует ли объект Email в ArrayCollection, но я должен выполнить проверку по электронной почте как строки (Entity содержит идентификатор и некоторые отношения с другими лицами, по этой причине я использую отдельную таблицу, которая сохраняет все электронные письма).Как использовать метод 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; 
     } 
    } 

Но чтение ArrayCollection класс я видел метод exists что, кажется, более elgant способ сделать то же самое, что я сделал.

Но я не знаю, как его использовать: может кто-нибудь объяснить мне, как использовать этот метод с учетом кода выше?

ответ

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

Смежные вопросы