[英]How to use Doctrine's ArrayCollection::exists method
I have to check if an Email
entity already exists in the ArrayCollection
but I have to perform the check on the emails as strings (the Entity contains an ID and some relations to other entites, for this reason I use a separate table that persists all emails).我必须检查ArrayCollection
是否已经存在Email
实体,但我必须将电子邮件作为字符串进行检查(实体包含一个 ID 和与其他实体的一些关系,因此我使用一个单独的表来保存所有电子邮件)。
Now, in the first I wrote this code:现在,首先我写了这段代码:
/**
* 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;
}
}
But reading the ArrayCollection
class I seen the method exists
that seems to be a more elgant way of doing the same thing I did.但是在阅读ArrayCollection
类时,我看到exists
的方法似乎是一种更优雅的方式来做同样的事情。
But I don't know how to use it: can someone explain me how to use this method given the code above?但我不知道如何使用它:有人可以解释我如何使用上面的代码来使用这种方法吗?
Of course, in PHP a Closure is a simple Anonymous functions .当然,在 PHP 中一个Closure是一个简单的匿名函数。 You could rewrite your code as follow:您可以按如下方式重写代码:
$exists = $this->emails->exists(function($key, $element) use ($email){
return $email->getEmail() === $element->getEmail()->getEmail();
});
Hope this help希望这有帮助
Thank you @Matteo!谢谢@Matteo!
Just for completeness, this is the code with which I came up:为了完整起见,这是我想出的代码:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.