Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 4. ServiceEntityRepository vs EntityRepository

Tags:

symfony4

Why do I need to extend ServiceEntityRepository in my repository? In Symfony 3.4, I always extended EntityRepository. With ServiceEntityRepository I have a strange problem described here Symfony 4. InheritanceType("JOINED") and ParamConverter. Strange phenomenon

like image 879
olek07 Avatar asked Mar 15 '19 09:03

olek07


1 Answers

Here my 2 cents: You don't need but you should. Why ? Because it's allow you to use autowiring (which is a big enhancement in SF4 and a pleasur to develop with)

class ProductRepository extends ServiceEntityRepository
{
    public function __construct(RegistryInterface $registry)
    {
        parent::__construct($registry, Product::class);
    }
}

Then you can autowring everywhere like that:

// From product controller
public function show(?int $id, ProductRepository $repository)
{
    $product = $repository->find($id);
    if (!$product) {
        throw $this->createNotFoundException(
            'No product found for id '.$id
        );
    }

    return new Response('Check out this great product: '.$product->getName());
}

If you don't want, no worries just use the old way:

// From product controller
public function show(?int $id, EntityManagerInterface $manager)
{
    $product = $manager->getRepository(Product::class)->find($id);
    // or this one but only in a controller which extend AbstractController
    $product = $this->getDoctrine()->getRepository(Product::class)->find($id);
    if (!$product) {
        throw $this->createNotFoundException(
            'No product found for id '.$id
        );
    }

    return new Response('Check out this great product: '.$product->getName());
}
like image 165
GuillaumeL Avatar answered Sep 30 '22 06:09

GuillaumeL