从实体对象symfony 2调用doctrine

Ris*_*s90 3 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

Chr*_*nel 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]
Run Code Online (Sandbox Code Playgroud)

你/包/服务/ 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

$blogEntry->setBlog($blog);
Run Code Online (Sandbox Code Playgroud)