简体   繁体   English

如何检查是否在Doctrine2存储库中找到了对象?

[英]How do I check if object was found in a Doctrine2 repository?

I am finding a entity by its PK as follow: 我通过它的PK找到一个实体如下:

$ent = $em->getRepository('AppBundle:Representative')->find($id)

What is the right way to check whether $ent is a real Representative object or not? 检查$ent是否是真正的代表对象的正确方法是什么? What I mean with real is that $ent currently exists on DB and was returned since I am planning to use the same results for INSERT and UPDATE . 我的真实含义是$ent当前存在于DB上并且由于我计划对INSERTUPDATE使用相同的结果而被返回。 In pseudo-code what is on my head is: 在伪代码中,我的头脑是:

if (ent is Representative)
{
    // Update its values
} else {
    // Create a new Representative
}

I was thinking in use is_object() or even instanceof but I am not sure if they will do the job or if $ent will be an object even if Representative doesn't exist on DB. 我在考虑使用is_object()甚至是instanceof但我不确定他们是否会完成这项工作,或者即使代理在DB上不存在, $ent也是一个对象。 Any advice on this? 有什么建议吗? How I can achieve that? 我怎么能做到这一点?

EntityRepository::find() method (which you use) returns an object , or null if the object couldn't be found in the database. EntityRepository::find()方法(您使用)返回一个object ,如果在数据库中找不到该object ,则返回null All of the following conditions are valid: 以下所有条件均有效:

if ($entity) {
}

if (null !== $entity) {
}

if ($entity instanceof Representative) {
}

Choose one that suits your coding standards the best, and use it consistently. 选择最适合您编码标准的产品,并始终如一地使用。

If you don't need to create a new object if it's not found, better throw an exception and handle it appropriately. 如果您不需要创建新对象,则最好抛出异常并适当地处理它。

How about this: 这个怎么样:

$product = $this->getDoctrine()
        ->getRepository('AppBundle:Product')
        ->find($id);

    if (!$product) {
        throw $this->createNotFoundException(
            'No product found for id '.$id
        );

Source: click me 来源: 点击我

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM