Let’s continue our series with a tutorial about Models in Magento 2. You can check my previous posts about Magento 2.
- 1. Install Magento 2 locally on MAMP
- 2. Create a new module in Magento 2
- 3. Database Install Scripts in Magento 2
- 4. Database Upgrade Scripts in Magento 2
First of all Models we store the code in Model folder of our project. The most basic entity in this namespace is ResourceModel because it’s communicating directly with the database.
Resource Models
Resource Models are stored in Model/ResourceModel folder of our project. Here we create our file Item.php and implement the Item class that extends AbstractDb. It’s mandatory to implement the constructor of the class. Here we define the table to which the resource is connected.
<?php namespace Mesteru\FirstModule\Model\ResourceModel; use Magento\Framework\Model\ResourceModel\Db\AbstractDb; class Item extends AbstractDb { protected function _construct() { $this->_init('mesteru_sample_item', 'id'); } }
Models
Now that we have the Resource Model we create our Model class. In the Model folder we create the file Item.php where we define the Item model class that extends AbstractModel class. In this class it’s also mandatory to implement the constructor where we call the _init method giving our Resource Model as parameter.
<?php namespace Mesteru\FirstModule\Model; use Magento\Framework\Model\AbstractModel; class Item extends AbstractModel { protected $_eventPrefix = 'mesteru_sample_item'; protected function _construct() { $this->_init(\Mesteru\FirstModule\Model\ResourceModel\Item::class); } }
Collections
Now lets create a Collection, which is actually a Resource Model. Because of that we create the file Collection.php in the ResourceModel/Item folder. We define the Collection class that extends AbstractCollection. For this class we need to define the $_idFieldName property. In the constructor we call the _init method giving as parameters our Model and Resource Model.
<?php namespace Mesteru\FirstModule\Model\ResourceModel\Item; use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection; use Mesteru\FirstModule\Model\Item; use Mesteru\FirstModule\Model\ResourceModel\Item as ItemResource; class Collection extends AbstractCollection { protected $_idFieldName = 'id'; protected function _construct() { $this->_init(Item::class, ItemResource::class); } }
Conclusion
This is how we create Models in Magento 2. Now the data is called from our mesteru_sample_item table by our Resource Model and we are able to create Models that are using the Resource Model to call or write data and access Collections.
Get the Code
You can get the complete code on my github profile here.




