Doctrine2存储库是保存实体的好地方吗? [英] Are Doctrine2 repositories a good place to save my entities?

查看:150
本文介绍了Doctrine2存储库是保存实体的好地方吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我阅读关于存储库的文档时,通常可以使用实体&

When I read docs about repositories, it is often to work with entities & collection but in a "read-only" manner.

从来没有例子,其中存储库的方法如 insertUser(User $ user) updateUser(User $ user)

There are never examples where repositories have methods like insertUser(User $user) or updateUser(User $user).

但是,使用SOA时,服务不应该与实体经理合作(对,不是吗?)所以:

However, when using SOA, Service should not be working with Entity Manager (that's right, isn't it?) so:


  1. 我的服务是否应该注意全球EntityManager? li>
  2. 如果我的服务只知道已使用的存储库(也就是说,UserRepository& ArticleRepository)

从这两个问题,另一个,应该我的服务明确地 persist()&

From that both questions, another one, should my service ever explicitly persist() & flush() my entities ?

推荐答案

是的,存储库通常被使用仅供查询。

Yes, repositories are generally used for queries only.

这是我做的。 服务层管理持久性。控制器层知道服务层,但不知道模型对象如何被保留,也不知道它们来自哪里。对于控制器层关心的是要求服务层持久化并返回对象 - 它不关心它实际上如何实现。

Here is how I do it. The service layer manages the persistence. The controller layer knows of the service layer, but knows nothing of how the model objects are persisted nor where do they come from. For what the controller layer cares is asking the service layer to persist and return objects — it doesn't care how it's actually done.

服务层本身非常适合了解持久层:实体或文档管理器,存储库等。

The service layer itself is perfectly suitable to know about the the persistence layer: entity or document managers, repositories, etc.

这里有一些代码可以使其更清楚:

Here's some code to make it clearer:

class UserController
{
    public function indexAction()
    {
        $users = $this->get('user.service')->findAll();
        // ...
    }

    public function createAction()
    {
        // ...
        $user = new User();
        // fill the user object here
        $this->get('user.service')->create($user);
        // ...
    }
}

class UserService
{
    const ENTITY_NAME = 'UserBundle:User';

    private $em;

    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    public function findAll()
    {
        return $this->em->getRepository(self::ENTITY_NAME)->findAll();
    }

    public function create(User $user)
    {
        // possibly validation here

        $this->em->persist($user);
        $this->em->flush($user);
    }
}

这篇关于Doctrine2存储库是保存实体的好地方吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆