Repository pattern in Magento 2
April 17, 2018 | Write by opensource-services
In case you haven’t noticed, Magento 2 recently marked all model CRUD operations as deprecated, in favor of following repository pattern. This article will be a short overview for those who are new to this concept.
What is repository pattern?
So what is this repository pattern? In short – it is a design pattern which allows code separation between data retrieval and business logic. For this purpose in Magento 2, you will (mostly) encounter two objects:
Data model – An object used to store retrieved information which should further be used in your business logic.
Repository – An object that is used for talking to your persistent storage (most likely MySQL).
What are the benefits of this approach?
There are several benefits to this approach. First of all, there is separation of concerns. By using repository pattern, you are clearly separating business logic from the code that is responsible for storing such data. This produces cleaner code, that is easier to read and modify. In the end, it is easier to optimize your code, as database queries are isolated in one place and modifying them should not (theoretically) influence the rest of the code and its dependencies.
Another thing that comes in handy here is, that code is easier to test, at least the business part. By having load process isolated to repository object, it is easier to swap it during testing and use any preconfigured data set.
On the other hand, one thing that you will find difficult to achieve is lazy loading. Consider a situation where you are loading one model that triggers loading of data that is expensive, but you might not need it at all.
How does this work in Magento?
Basically your code would simply look something like this:
// Retrieve data from persistent sotrage $model = $modelRepository->loadById($id); // Retrieve data from model $name = $model->getName(); // Change data on model $model->setActive(true); // Save the changes $modelRepository->save($model);
As you can see, load and save is managed through repository, while data management itself is done, just like the old times in Magento 1.
And that is it. From here on, I can only suggest links for further research:
- Magento documentation – service contracts
- Magento documentation – data interfaces
- Understanding object repositories by Alan Storm
And most importantly, Magento 2 source code, for an example here.