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

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 a 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.


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.

Enjoy.


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