Shopware 6: What is the proper way to get an entity repository?

Viewed 55

I have noticed three different ways to get an entity repository from within a Shopware 6 controller or service.

  1. Inject the repo as a container parameter, e.g.
<argument type="service" id="product.repository"/>
  1. Retrieve it from the DefinitionInstanceRegistry, e.g.
$productRepository =  $this->definitionInstanceRegistry->getRepository(ProductDefinition::ENTITY_NAME);
  1. Get it from the container directly e.g.
$productRepository = $this->container->get('product.repository');

As it appears to me all three methods produce the same result. What are the differences, if any, and what is the recommended approach to use?

1 Answers

Injecting a service as an argument is always preferable. For a more detailed explanation from an architectural point of view, I recommend the accepted answer of this question.

As for the DefinitionInstanceRegistry it depends whether your service has to handle a variety of different entities, e.g. when you want to dynamically decide which kind of entity to read or write. Then it may make sense to use the registry instead of injecting a larger number of single repositories but it shouldn't be your go-to solution at all.

Related