2

I am trying to establish what the best practise is regarding the placement of custom repositories.

Accordingly, my question is ; what is the correct location to place a model's repository in a custom module.

in magento's 'customer module' its placed in the ResourceModel folder:

magento\module-customer\Model\ResourceModel\CustomerRepository.php

However in the product Module its place in the model folder:

magento\module-catalog\Model\ProductRepository.php
1

There is a reference to this here: https://devdocs.magento.com/guides/v2.1/extension-dev-guide/persistent-entities.html#repositories

Firstly, this paragraph talks about repositories generally and mentions the possibility of either location:

We recommend placing the class files for repositories under the Model or Model/ResourceModel directory inside your module’s root directory.

It's not immediately obvious without reading further, but here's my interpretation of what the doc goes on to say. Please, if anybody else has another interpretation of this, please contribute it.

So, it goes on to say this:

Different parts of the application can use your repository to load entities. To prevent loading of the same data from the database more than once, use a registry inside the repository. For an example of this strategy, take a look at the Magento\Customer\Model\ResourceModel\CustomerRepository class.

The important part here is: To prevent loading of the same data from the database more than once, use a registry inside the repository.

Now the next section talks about Resource Models

Resource models contain logic that allow entities to be persistent. They help decouple the model layer from the data layer by acting as an intermediate mapping layer between the two. These classes provide the interface to manipulate data to the model layer while implementing code that is specific to the data layer. We recommend you put resource models under the Model/ResourceModel directory inside your module’s root directory.

So logically, by using a registry to enable persistence, the repository is a Resource Model.

Given your example, if your repository is behaving like Magento\Customer\Model\ResourceModel\CustomerRepository in that it is using a registry inside the repository allowing persistence, it belongs in Model/ResourceModel/. If it is not, like Magento\Catalog\Model\ProductRepository, it just belongs in Model/.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.