One entity, two repositories in symfony

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

Tags:

Symfony