从实体对象symfony 2调用doctrine

时间:2012-06-26 14:19:32

标签: php symfony

我正在调查symfony 2框架。在我的示例应用程序中,我有Blog实体和BlogEntry实体。它们与一对多关系相关联。这是BlogEntry类:

class BlogEntry
{
    ....
    private $blog;
    ....
    public function getBlog()
    {
        return $this->blog;
    }

    public function setBlog(Blog $blog)
    {
        $this->blog = $blog;
    }
}

我想将方法​​setBlogByBlogId添加到BlogEntry类,我这样看:

public function setBlogByBlogId($blogId)
    {
        if ($blogId && $blog = $this->getDoctrine()->getEntityManager()->getRepository('AppBlogBundle:Blog')->find($blogId))
        {
            $this->setBlog($blog);
        }
        else
        {
            throw \Exception();
        }
    }

这是否可以在模型类中获得学说?从Symfony 2 MVC架构的角度来看这是正确的吗?或者我应该在我的控制器中执行此操作?

1 个答案:

答案 0 :(得分:5)

在尝试在BlogEntry实体上设置之前,您应该使用blogId在博客库中查询博客对象。

获得博客对象后,您只需在BlogEntry实体上调用setBlog($ blog)即可。

您可以在控制器中执行此操作,也可以创建博客服务(博客管理器)来为您执行此操作。我建议你在服务中这样做:

在您的/ Bundle / Resources / config / services.yml中定义您的服务:

services
    service.blog:
    class: Your\Bundle\Service\BlogService
    arguments: [@doctrine.orm.default_entity_manager]

您/包/服务/ BlogService.php:

class BlogService
{

    private $entityManager;

    /*
     * @param EntityManager $entityManager
     */
    public function __construct($entityManager)
    {
        $this->entityManager = $entityManager;
    }

    /*
     * @param integer $blogId
     *
     * @return Blog
     */
    public function getBlogById($blogId)

        return $this->entityManager
                    ->getRepository('AppBlogBundle:Blog')
                    ->find($blogId);
    }
}

然后在你的控制器中你可以去:

$blogId = //however you get your blogId
$blogEntry = //however you get your blogEntry

$blogService = $this->get('service.blog');
$blog = $blogService->getBlogById($blogId);

$blogEntry->setBlog($blog);