2016-10-21 5 views
6

मुझे यह जांचना है कि Email इकाई ArrayCollection में पहले से मौजूद है या नहीं, लेकिन मुझे ईमेल पर स्ट्रिंग के रूप में जांच करना है (इकाई में एक आईडी है और अन्य entites के लिए कुछ संबंध हैं, इस कारण से मैं एक अलग टेबल का उपयोग करता हूं जो सभी ईमेल जारी रखता है)।Doctrine's ArrayCollection का उपयोग कैसे करें :: मौजूद विधि

अब, में पहली मैं इस कोड लिखा है:

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

संबंधित मुद्दे