Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One entity, two repositories in symfony

Tags:

symfony

I would like use 2 repository for 1 entity.

The reason is : I have 2 bundles, both bundle use the same entity. I wish to separate both functionalities. Sometimes I need specific queries into bundle.

It is possible to have 1 repository into a bundle and a second repository in the other one ? Maybe it's a wrong way ?

If someone have an idea.

Thx !

like image 878
lala Avatar asked Oct 20 '15 07:10

lala


2 Answers

2019 Update

I'd create 2 repositories. It makes no sense to add all methods to one repository, just because they share the entity. We could end up with 30 methods per repository this way.

First repository

namespace App\Repository;

use App\Entity\Post;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;

final class FrontendPostRepository
{
    /**
     * @var EntityRepository
     */
    private $repository;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->repository = $entityManager->getRepository(Post::class);
    }

    /**
     * @return Post[]
     */
    public function getAll(): array
    {
        // ...
    }
}

...and 2nd repository

namespace App\Repository;

use App\Entity\Post;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;

final class AdminPostRepository
{
    /**
     * @var EntityRepository
     */
    private $repository;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->repository = $entityManager->getRepository(Post::class);
    }

    /**
     * @return Post[]
     */
    public function getUnpublished(): array
    {
        // ...
    }
}


You can read more about this concept and whys in How to use Repository with Doctrine as Service in Symfony post

like image 189
Tomas Votruba Avatar answered Oct 20 '22 01:10

Tomas Votruba


Well I don't really know it's a good practice but you can create a repository without linked entity (I mean, not with ORM annotation)

So I just create this in my service.yml :

renting.metadata.car:
    class: Doctrine\ORM\Mapping\ClassMetadata
    arguments: [ %car% ]

And this :

repair.repository.car:
    class: carRepository
    arguments: [@doctrine.orm.entity_manager, @renting.metadata.car]

That's works

like image 37
lala Avatar answered Oct 20 '22 01:10

lala