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
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With