Magento2 – Difference Between Models and Data Models

magento-2.1magento2

I'm aware that Magento 2 introduced data models as part of the service contract architecture. Data models usually implement interfaces defined in Api/Data/ of a module.

But, Magento seems to have retained the old models too.

Let's take an example to module-customer.

  • Data model interface defined in Api/Data/CustomerInterface.php
  • The above interface is implemented in Model/Data/Customer.php
  • The data model has all the getter and setter function for the customer variables, as one would expect
  • In addition to the above there is also a Model/Customer.php. This too has getter and setter function. This is more like a Magento 1 model that connects to the ResourceModel (Model/ResourceModel/Customer.php)
  • In Model/ResourceModel/CustomerRepository.php, various function collect data from the Magnento 1 model, transfer them to the data model, and then return the data model.

Why does one need the old model? Why can't the data model directly connect with the ResourceModel?

Best Answer

My explaination:

It is very difficult to understand the difference between a model and a data model. If I have to say in few words I could say that a model represents the engine and a data model represents its information.

In your example, with the customer entity, you can see for example how the method authenticate or validatePassword are kept in customer model since they are part of the engine and they are not going to directly handle information. On the other side, methods like getExtensionAttributes, since handling pieces of information are kept in the data model.

I think this is just a better project handling, just like the division between models and resource models, you could ask why you need them as well.

Why you need them:

If you want to expose customer information (for example) using API, you will need an interface (\Magento\Customer\Api\Data\CustomerInterface) with getters defining all the attributes of your entity, and if you have any other getter method not representing an information you want to expose (e.g.: getRandomConfirmationKey), you have a problem!

Thi is why, in my example, getRandomConfirmationKey is part of the model (\Magento\Customer\Model\Customer), while getFirstname is part of the data model.

A quick rule could be:

  • If your method represents a table column, an attribute or an entity information of any kind, then should go into data model.
  • If your method is an "action" on the information, it handles the information or you declare it in webapi.xml, then it should be a model method.

POST:

In few words: consider a data model almost as a DTO.

Related Topic