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

时间:2015-06-29 12:33:00

标签: php symfony doctrine-orm symfony-2.6 symfony-2.7

我通过其PK找到一个实体如下:

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

检查$ent是否是真正的代表对象的正确方法是什么?我对真实的意思是$ent目前存在于数据库中并且由于我计划对INSERTUPDATE使用相同的结果而被返回。在伪代码中,我的想法是:

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

我在考虑使用is_object()甚至是instanceof,但我不确定他们是否会完成这项工作,或者$ent是否会成为对象,即使代表不存在D B。有什么建议吗?我怎么能做到这一点?

2 个答案:

答案 0 :(得分:15)

如果在数据库中找不到该对象,则

EntityRepository::find()方法(您使用)返回objectnull。以下所有条件均有效:

if ($entity) {
}

if (null !== $entity) {
}

if ($entity instanceof Representative) {
}

选择最适合您编码标准的编码,并始终如一地使用。

如果您不需要创建新对象,则最好抛出异常并对其进行适当处理。

答案 1 :(得分:2)

这个怎么样:

window.setInterval(function(){
    var url = getCurrent();
    //start animation
    $('#slidesPartenairesHome').delay( 500 ).fadeTo(500, 0.3, function()
    {
        $(this).css('background-image', 'url(' + url + ')');
    }).fadeTo('slow', 1);
}, 1000);

// We start with index of 1 because we want to skip the first image, 
// Else we would be replacing it with the same image.
var index = 1;
     var arrayOfPartenaires = [
            "http://yourdomain.com/images/partenaires/a.png",
            "http://yourdomain.com/images/partenaires/b.png",
            "http://yourdomain.com/images/partenaires/c.png"
        ];

function getCurrent(){
    // We check if the index is higher than the ammount in the array.
    // If thats true set 0 (beginning of array)
    if (index > arrayOfPartenaires.length -1){
        index = 0;
    }
    var returnValue = index;
    index ++;
    return arrayOfPartenaires[returnValue];       
}

来源:click me