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?
Best Answer
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 thedatabase
and get/set data for it onsave()
andload()
.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 thedatabase
.During development, if working with
collections
that have lot ofattributes
,filters
, and possibly a futurelarge dataset
, we might want to useSQL logging
to record actualSQL 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.when you use repositories you adhere to
Magento 2
servicecontracts
, which means thatservice interfaces
anddata 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 theattributes
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.