Php 如何使用条令';s ArrayCollection::exists方法

Php 如何使用条令';s ArrayCollection::exists方法,php,symfony,doctrine-orm,doctrine,Php,Symfony,Doctrine Orm,Doctrine,我必须检查电子邮件实体是否已存在于阵列集合中,但我必须以字符串形式对电子邮件执行检查(该实体包含一个ID以及与其他实体的一些关系,因此我使用一个单独的表来保存所有电子邮件) 现在,在第一部分中,我编写了以下代码: /** * A new Email is adding: check if it already exists. * * In a normal scenario we should use $this->emails->contain

我必须检查
电子邮件
实体是否已存在于
阵列集合
中,但我必须以字符串形式对电子邮件执行检查(该实体包含一个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
类时,我看到了一种方法,这种方法似乎是一种更有效的方法,可以完成与我相同的事情

但是我不知道如何使用它:有人能解释一下,在上面的代码中如何使用这个方法吗?

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

$exists =  $this->emails->exists(function($key, $element) use ($email){
    return $email->getEmail() === $element->getEmail()->getEmail();
});
希望这些帮助

谢谢@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;
}

为什么即使未使用$key,我们也必须编写它?我记得关于exists的
闭包的签名function@NicklasMandrupFrederiksenexists函数的签名是这样的,因此如果您只编写
函数($element)
PHP不会抛出任何错误,但是
$element
实际上是键(索引,一个int)