When Should We Use a Repository and Factory in Magento 2?



I have gone through a couple of tutorials in Magento 2, and this confuses me a little. I can see there are basically two ways by which we can read/write business entities:

Retrieve Data

Using A Factory Approach

$object = $this->myFactory->create();

Using A Repository Approach

$repo   = $this->myRepository();
$object = $repo->getById($myId);

Save Data

Using A Factory Approach

$object = $this->myFactory->create();
$object->setData('something', 'somethingDifferent')->save();

Using A Repository Approach

$repo   = $this->myRepository();
$object = $repo->getById($myId);
$object->setData('something', 'somethingDifferent');

I can also see that, both a repository and a factory class can be injected using dependency injection. This is confusing at least for me.

When should we use a repository approach and a factory approach? What is the best practice we need to follow?

Rajeev K Tomy

Posted 2017-02-04T04:48:11.877

Reputation: 13 126



If there is a repository and it does what you need well, always prefer the repository.

Repositories are part of the Service Contracts (they are implementations of interfaces in Api), this means they are meant as public interface to other modules.

Use Repositories for full loading

$model->load() is not part of the service contract. I had a question on that particular topic, you might find the answers useful: Is there ever a reason to prefer $model->load() over service contracts?

Use Factories to create new entities

Repositories do not come with methods to create a new entity, so in that case you will need a factory. But use the factory for the interface, such as Magento\Catalog\Api\Data\ProductInterfaceFactory - it will create the right implementation based on DI configuration.

Then use the repository->save() method to save it.

Use Collection Factories if you need more control

The following is not official Magento best practice, but currently repositories do not give you fine control over what to load. The search criteria API lets you define filters, but for example there is no way to select particular EAV attributes or specify which index tables to join.

These are implementation details, hidden from the service contract APIs, but often these implementation details matter and you get poor performance if you ignore them. For that reason, as soon as the repositories are limiting me I don't hesitate anymore to use the underlying collections.

Fabian Schmengler

Posted 2017-02-04T04:48:11.877

Reputation: 49 110

1Could you give a code example about use Factories to create new entities, the explanation miss some details and hard to understand. Thank you very much. – Key Shang – 2017-11-14T09:01:32.560

@Key does this help? http://devdocs.magento.com/guides/v2.2/extension-dev-guide/factories.html

– Fabian Schmengler – 2017-11-14T09:21:54.697

Thanks. but the use the factory for the interface, such as Magento\Catalog\Api\Data\ProductInterfaceFactory - it will create the right implementation based on DI configuration. is the point which I can not understand, the dev guides doesn't introduce the InterfaceFactory , how to use repository->save() method to save new entities? I can just only use factory to save new entities, not repository. – Key Shang – 2017-11-14T10:43:59.603


Good question.

Even if both Repositories and Factories let us access an Entity I think we should focus on their responsibility.

From Magento documentation: "Factories are service classes that instantiate non-injectable classes, that is, models that represent a database entity. They create a layer of abstraction between the ObjectManager and business code."

From Alan Storm's article: "A repository object is responsible for reading and writing your object information to an object store"

My interpretation is: If our purpose is to work with non-injectable (so called "newable") objects we should use Factories; if our focus is on searching/reading/writing objects within an object store we should use Repositories.

This is my idealistic approach to the topic; keep in mind that actual implementation may force us to mess up things, as pointed out by Alan.


Alessandro Ronchi

Posted 2017-02-04T04:48:11.877

Reputation: 2 696


I would say the way forward it's to start using repositories as they allow code separation between data reading/writing and business logic.

There is a very detailed article written by Alan Storm about this, explaining how to use repositories but also looking into some drawbacks of this new method: http://alanstorm.com/magento_2_understanding_object_repositories/

Also, from the Magento documentation, explaining the benefits of this new aproach: http://devdocs.magento.com/guides/v2.0/extension-dev-guide/service-contracts/service-contracts.html

Marina Gociu

Posted 2017-02-04T04:48:11.877

Reputation: 1 061

1thanks for the answer. I actually get this doubt on my head from alanstorm's article ifself. :) – Rajeev K Tomy – 2017-02-04T09:02:31.707

2Indeed, it leaves you thinking, but that is probably a good thing. Even if this is the best practice suggested by Magento, it doesn't mean developers can not raise questions and critique some aspects of it. Also, there are still situations that aren't covered by the repositories. However, in the context of building extensions that won't break on future releases using repositories should be considered. Also, I'm sure they will develop further and offer more coverage on what developers need. – Marina Gociu – 2017-02-04T09:18:07.897

I 100% agree with your comment. I really hope so. Also please see fabian's answer too. – Rajeev K Tomy – 2017-02-04T09:20:58.973

Yes, I saw :) already upvoted his answer. Thanks for the great question! – Marina Gociu – 2017-02-04T09:24:23.883


Hope this answer might help other extension developers as well.

We have to save model using Repository only.

  1. Factory Model in Magento 2 hold very limited data.
  2. On the Other hand, Repository Model contains all data, in case of eav attributes related to customer, products , etc.
  3. For saving model, always use Repository to save any entity, if factory model is used for saving model, it deletes all non-system eav attributes related to that entity (customer, product, etc.).

  4. For loading model purpose, Repository are best option to get model using getById() method.

I will recommend to use Repository as much as possible specially for model save purpose.


Posted 2017-02-04T04:48:11.877

Reputation: 31


Now load,save,delete methods (models) are deprecated.So we can use resource model or repository.

Magento now using entity manager concept for save,delete,load operations.

Resource models have entity manager object to fulfil those operations.

$categoryModel = $this->_objectManager->create('\Magento\Catalog\Model\CategoryFactory')->create();        
  $categoryResource = $this->_objectManager->create('\Magento\Catalog\Model\ResourceModel\Category');        
  $categoryResource->load($categoryModel, 3);        
  echo $categoryModel->getName();

Siva Kumar Koduru

Posted 2017-02-04T04:48:11.877

Reputation: 61