Symfony - How to access entity's repository Symfony - How to access entity's repository symfony symfony

Symfony - How to access entity's repository


In the Doctrine world the entity is just supposed to be an anaemic model of getters and setters (and add or removes) so injecting the repository would be wrong thing to do.

It all depends on how coupled you want to be to Doctrine. If you are fine with passing the @doctrine service around then you could just using something like:

$this->repository = $doctrine->getRepository('CmsBundle:Page');

.. but then that, as mentioned, would require you to pass the @doctrine service into every object. This would mean that if you ever decided to not use Doctrine for whatever reason, you would need to refactor all of your code to fit your new methodology (whatever that may be), but this may be a non-issue for you. Also, the repository would be type-hinted so there is no assurance (beyond checking if it is the correct class in code) to guarantee that it is the correct service.

In my opinion the cleanest way to do it is to create a service like:

XML

<service id="cms.page_repository"    class="Acme\CmsBundle\Repository\PageRepository">    <factory service="doctrine" method="getRepository" />    <argument>AcmeDemoBundle:ExampleRepository</argument></service>

YAML

cms.page_repository:    class: Acme\CmsBundle\Repository\PageRepository    factory: [ @doctrine, 'getRepository' ]

.. and then you can pass your repository service around where ever you want without the need of using the doctrine service in your actual code. With this approach, if you ever decide to move away from Doctrine, you only need to change the service definitions rather than needing to refactor everything. Also due to the fact that you are creating the service of your specific repository you can use type hinting in your __construct to guarantee the correct service is being injected like:

public function __construct(PageRepository $repository){    $this->repository = $repository;}


For me, none of your suggestions are correct.
Because I do not understand why you need to create a service of your entity.
If you need access to this entity the only thing you need is to have access to doctrine.
And doctrine has a service (@doctrine).
It's up to you to prepare in the construct to have access only to that entity.

Statics are to forgotten:

And what you submit in method 5 is not correct, your Product entity already access to entityManager via ProductRepository with the getEntityManager() method.


I'll suggest you to use method 4, your service will follow Single Resposability Principe as it only do one thing: giving you an access to all your repositories.

This service will be mostly as a dependency in other services. For controllers, I suggest you to create a custom controller base class with the same helper functions.

About code duplications, traits may be the solution. Even with the numbers of methods if you use a trait by "category"