如何使用Doctrine的ArrayCollection :: exists方法

时间:2016-10-21 10:59:30

标签: php symfony doctrine-orm doctrine

我必须检查Email中是否已存在ArrayCollection实体,但我必须将电子邮件检查为字符串(实体包含ID以及与其他实体的某些关系,这个原因我使用了一个单独的表来保存所有电子邮件。)

现在,在第一篇文章中我写了这段代码:

    /**
     * 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,这似乎是我做同样事情的一种更为优雅的方式。

但我不知道如何使用它:根据上面的代码,有人可以解释一下如何使用这种方法吗?

2 个答案:

答案 0 :(得分:20)

当然,在PHP中,Closure是一个简单的Anonymous functions。您可以按如下方式重写代码:

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

希望这个帮助

答案 1 :(得分:2)

谢谢@Matteo!

为了完整起见,这是我提出的代码:

function file_to_arr($file)
{
$myfile = fopen($file, "r") or die("Unable to open file!");
// Output one line until end-of-file
while(!feof($myfile)) {
     $exploded_data = explode(": ",fgets($myfile));
     if(in_array("Info",$exploded_data))
    $text[$exploded_data[0]] = $exploded_data[1].' : '.$exploded_data[2];
    else
     $text[$exploded_data[0]] = $exploded_data[1];
}
fclose($myfile);
return $text;
}

print_r(file_to_arr('tt.txt'));

Array ( [Host] => x-sgdo43.serverip.co [Username] => mywebsite.com-user [Password] => pass [Port] => 443 [Info] => Date Expired : 26-October-2016 )