Exploring Magento 2.2 UI Component – Part 2 Creating Model, Resource Model and Collection classes
In our Last Tutorial Exploring Magento 2.2 UI Component – Part 1 we have created a custom database table, now we will create the appropriate MODEL, RESOURCE MODEL and Collection Classes to fetch the data from our custom table
Step 1:- Lets create our model class. The Model Class defines the entity we are storing and retrieving from database.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php namespace Mydons\Tradeshows\Model; class Shows extends \Magento\Framework\Model\AbstractModel implements \Magento\Framework\DataObject\IdentityInterface { const CACHE_TAG = 'tradeshows'; protected function _construct() { $this->_init('Mydons\Tradeshows\Model\ResourceModel\Shows'); } public function getIdentities() { return [self::CACHE_TAG . '_' . $this->getId()]; } } |
In the above code the constant CACHE_TAG denotes our custom table name which we created in the last tutorial. The _construct method in turn calls the _init method with the RESOURCE Model as argument. The RESOURCE Model class is actually responsible for fetching the data from custom table
Step 2:- Once the Model class is created the next step would be to create the RESOURCE Model class.
1 2 3 4 5 6 7 8 9 |
<?php namespace Mydons\Tradeshows\Model\ResourceModel; class Shows extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb { protected function _construct() { $this->_init('tradeshows','entity_id'); } } |
Resource Model class extends from the base class \Magento\Framework\Model\ResourceModel\Db\AbstractDb. The _construct method calls an _init method. In the _init Method call the first argument represents our custom table name, the second argument represents the PRIMARY KEY of our custom table in our case it is entity_id
Step 3:- In the Last step of our tutorial we will create the Collection class. The Collection is used to fetch the list of models i.e a collection is actually a collection of model objects. In the collection class _construct we will pass the Model class name, Resource Model class name as arguments.
1 2 3 4 5 6 7 8 9 |
<?php namespace Mydons\Tradeshows\Model\ResourceModel\Shows; class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection { protected function _construct() { $this->_init('Mydons\Tradeshows\Model\Shows','Mydons\Tradeshows\Model\ResourceModel\Shows'); } } |