2016-10-21 20 views
6

Tôi phải kiểm tra xem thực thể Email đã tồn tại trong ArrayCollection hay chưa. Tôi phải thực hiện kiểm tra email dưới dạng chuỗi (thực thể chứa ID và một số mối quan hệ với các đơn vị khác) vì lý do này tôi sử dụng một bảng riêng biệt mà vẫn tồn tại tất cả các email).Cách sử dụng ArrayCollection của Doctrine :: Phương thức tồn tại

Bây giờ, trong lần đầu tiên tôi đã viết mã này:

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

Nhưng đọc lớp ArrayCollection Tôi thấy phương pháp exists điều đó dường như là một cách elgant hơn để làm điều tương tự tôi đã làm.

Nhưng tôi không biết cách sử dụng: ai đó có thể giải thích cho tôi cách sử dụng phương pháp này cho mã ở trên không?

Trả lời

8

Tất nhiên, trong PHP Closure là đơn giản Anonymous functions. Bạn có thể viết lại mã của bạn như sau:

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

Hope trợ giúp này

1

Cảm ơn bạn @Matteo!

Chỉ cần cho đầy đủ, đây là đoạn code mà tôi đã đưa ra:

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 tốt công việc! – Matteo

Các vấn đề liên quan