Are Doctrine2 repositories a good place to save my entities?

后端 未结 3 473
我在风中等你
我在风中等你 2021-01-29 20:20

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

There are never examples where repositories have m

3条回答
  •  野性不改
    2021-01-29 21:04

    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);
        }
    }
    

提交回复
热议问题