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

2022-08-30 20:49:37

我必须检查实体中是否已经存在,但我必须以字符串的形式对电子邮件执行检查(实体包含一个ID和与其他实体的一些关系,因此我使用一个单独的表来保存所有电子邮件)。EmailArrayCollection

现在,在第一个代码中,我写了这个代码:

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

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


答案 1

当然,在 PHP 中,闭包是一个简单的匿名函数。您可以按如下方式重写代码:

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

希望这有帮助


答案 2

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

推荐