2016-10-21 64 views
6
varlığının ArrayCollection sürümünde var olup olmadığını kontrol etmeliyim, ancak e-postaların denetimini dizeler olarak yapmam gerekiyor (Varlık bir kimlik ve diğer girdilerle bazı ilişkiler içeriyorsa, bu nedenle tüm e-postalarda kalıcı olan ayrı bir tablo kullanıyorum).

Doctrine's ArrayCollection :: varolan yöntem

Şimdi, ilk ben bu kodu yazdım içinde:

/** 
    * 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; 
     } 
    } 

Ama yaptığının aynısını yapmanın daha elgant yol olarak görünüyor yöntemi exists görülen ArrayCollection sınıf okuma.

Ama nasıl kullanacağımı bilmiyorum: Birisi yukarıdaki kodu kullanarak bu yöntemin nasıl kullanılacağını açıklayabilir mi?

cevap

8

Elbette, PHP'de Closure basit bir Anonymous functions. Sen aşağıdaki gibi kodunuzu yazabilirsiniz:

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

Umut bu yardım

1

sen @Matteo ederiz!

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

hi @Aerendir iyi iş: Sadece şeyiyle

, bu şimdiye kadar geldiği ile kodudur! – Matteo