简体   繁体   English

从实体对象symfony 2调用doctrine

[英]Call doctrine from entity object symfony 2

I'm investigating symfony 2 framework. 我正在调查symfony 2框架。 In my sample app I have Blog entity and BlogEntry entity. 在我的示例应用程序中,我有Blog实体和BlogEntry实体。 They are connected with one to many relationship. 它们与一对多关系相关联。 This is BlogEntry class: 这是BlogEntry类:

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

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

I want to add method setBlogByBlogId to BlogEntry class, I see it this way: 我想将方法​​setBlogByBlogId添加到BlogEntry类,我这样看:

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

Is this any way to get doctrine in model class? 这是否可以在模型类中获得学说? Is this correct from the point of Symfony 2 MVC architecture? 从Symfony 2 MVC架构的角度来看这是正确的吗? Or I should do this in my controller? 或者我应该在我的控制器中执行此操作?

You should use your blogId to query your repository for the blog object before trying to set it on your BlogEntry entity. 在尝试在BlogEntry实体上设置博客对象之前,应使用blogId查询存储库中的博客对象。

Once you have the blog object, you can simply call setBlog($blog) on your BlogEntry entity. 获得博客对象后,您只需在BlogEntry实体上调用setBlog($ blog)即可。

You can either do this in your controller, or you can create a Blog Service (a Blog Manager) to do it for you. 您可以在控制器中执行此操作,也可以创建博客服务(博客管理器)来为您执行此操作。 I would recommend doing it in a service: 我建议在服务中这样做:

Define your service in Your/Bundle/Resources/config/services.yml: 在您的/ Bundle / Resources / config / services.yml中定义您的服务:

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

Your/Bundle/Service/BlogService.php: 你/包/服务/ 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);
    }
}

And then in your controller you can simply go: 然后在你的控制器中你可以简单地去:

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

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

$blogEntry->setBlog($blog);

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

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