Magento 2 - Difference between Model, ResourceModel. Collection and Repository
-
25-02-2021 - |
Question
I'm studying Magento and I'm confusing about the differences between these four layers. What I have understood is the following:
Model
Is the entity class with ONLY getters/setters and magic methods.
ResourceModel
Is the layer responsible of C.R.U.D operations. This class should contains ONLY the _construct
method to map my entity with the database table.
Collection
As the name suggested, it's a class that implements IterableInterface and give me only a list of Entity.
Repository
It's a class that expose API methods to the external and it's also used to execute operations to database. It's used to save/load/delete entity (internally I think that for these CRUD operations it should use the ResourceModel) and to expose methods to get collections of results.
EntityNameInterface
It's the interface that Model should implement.
EntityNameRepositoryInterface
It's the interface that Repository should implement.
But not all Magento modules work in this way, so there are modules that don't use this approach yet, but for compatibility reasons they use the old approach. Is it correct what I learned to it?
La solution
Models :-
Models are where your main business logic should be handled and is a single instance of an object.
The model will use the resource model
to talk to the database
and get/set data for it on save()
and load()
.
Resource Model :
A resource model is where your main C.R.U.D happens (Create, Read, Update and delete)
.
The resource model shouldn’t contain business logic however it will talk to the adapters
and basically talk to the database
.
Collections :
During development, if working with collections
that have lot of attributes
, filters
, and possibly a future large dataset
, we might want to use SQL logging
to record actual SQL queries hitting
the database server.
This might help us spot possible performance bottlenecks
and react on time, either by adding more limiting values to setPageSize or addAttributeToSelect , or both.
Repositories :
when you use repositories you adhere to Magento 2
service contracts
, which means that service interfaces
and data interfaces
are defined (but extensible by third-party modules).
Making it possible at run-time to change the result of the call to the getList()
method of a repository would violate this contract.
To retrieve the attributes
you need at run-time you can use collections.
Magento 2 framework itself makes an heavy use of collections
.
Otherwise you should implement a module which defines a new data interface (that is, the new set of attributes) for that entity.