Working with Models in Magento 2

 

This is part 2 of two parts article. See part 1 by clicking here.

This article is part 2 of “Working with Magento 2 Models”, which is talking about Model class file creation in Magento 2 and fetching data from database table using same. To see part 1 click on Creating Setup script in Magento 2.Goal of this article is to fetch data from database table

Important elements of using Models in Magento 2

Models are basically used to interact with Database.In this article we will see how to use Models to fetch data from database tables in Magento 2. Be careful, none of the class under model creation should not contain SQL directly.

In Magento 2 Models has three parts :-

  • Model Interface :- It’s an interface that creates setter, which is used to geter, setter methods for all the db fields. These methods are used for API related functionality.
  • Model : Models implement the Model Interface and it calls the Resource Model . It also uses caching tag and event prefix.
  • ResourceModel: It is used to contain overall database logic, it do not execute sql queries. It has two parts
    • ResourceModel
    • Collection

Lets see example of each section.

Creating Model Interface in Magento 2


File Path: app\code\Cutehits\First\Model\Api\Data\CustomuserInterface.php


<?php
namespace Cutehits\First\Model\Api\Data;
interface CustomuserInterface
{

}

Code Analysis: Since we are not looking for any API functionality into this tutorial so this class doesn’t contain anything.

Creating Model Class in Magento 2

File Path: app\code\Cutehits\First\Model\Customuser.php


<?php
namespace Cutehits\First\Model;
class Customuser extends \Magento\Framework\Model\AbstractModel implements \Magento\Framework\DataObject\IdentityInterface,
\Cutehits\First\Model\Api\Data\CustomuserInterface
{
const CACHE_TAG = 'cutehits_first_user';

protected $_cacheTag = 'cutehits_first_user';

protected $_eventPrefix = 'cutehits_first_user';

protected function _construct()
{
$this->_init('Cutehits\First\Model\ResourceModel\Customuser');
}

public function getIdentities()
{
return [self::CACHE_TAG . '_' . $this->getId()];
}

public function getDefaultValues()
{
$values = [];

return $values;
}
}

Code Analysis:
This model class will extends AbstractModel class Magento\Framework\Model\AbstractModel which further implements PostInterface and IdentityInterface \Magento\Framework\DataObject\IdentityInterface. The IdentityInterface will force Model class define the getIdentities() method that will return a unique id for each model. Main requirement of this interface is to provide unique id so in case your model required cache refresh after database operation and render information to the frontend page, then you must use this.

Next important part of this model class is its _construct() method. Which further calls _init() method. This _init() method will define the resource model which will actually fetch the information from the database. As above, we define the resource model Cutehits\First\Model\ResourceModel\Customuser . Another important part is some variable which you should you in your model:

  • $_eventPrefix – a prefix for events to be triggered
  • $_eventObject – a object name when access in event
  • $_cacheTag – a unique identifier for use within caching

Creating ResourceModel Class in Magento 2

As above ResourceModel has two parts:

a) ResourceModel: It has below code


<?php
namespace Cutehits\First\Model\ResourceModel;

class Customuser extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{
/**
* Date model
*
* @var \Magento\Framework\Stdlib\DateTime\DateTime
*/
protected $_date;

/**
* constructor
*
* @param \Magento\Framework\Stdlib\DateTime\DateTime $date
* @param \Magento\Framework\Model\ResourceModel\Db\Context $context
*/
public function __construct(
\Magento\Framework\Stdlib\DateTime\DateTime $date,
\Magento\Framework\Model\ResourceModel\Db\Context $context
)
{
$this->_date = $date;
parent::__construct($context);
}

/**
* Initialize resource model
*
* @return void
*/
protected function _construct()
{
$this->_init('cutehits_custom_users', 'user_id');
}

/**
* before save callback
*
* @param \Magento\Framework\Model\AbstractModel|\Mageplaza\HelloWorld\Model\Post $object
* @return $this
*/
protected function _beforeSave(\Magento\Framework\Model\AbstractModel $object)
{
$object->setUpdatedAt($this->_date->date());
if ($object->isObjectNew()) {
$object->setCreatedAt($this->_date->date());
}
return parent::_beforeSave($object);
}
}

Code Analysis: It has a constructor call and one hook calls. There are multiple hook methods can be implemented

  • afterLoad()
  • beforeSave()
  • afterSave()
  • beforeDelete()
  • afterDelete()
  • afterCommitCallback()
  • deleteCommit()

b) Collection.php

File: app\code\Cutehits\First\Model\ResourceModel\Customuser\Collection.php


<?php
namespace Cutehits\First\Model\ResourceModel\Customuser;

class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
protected $_idFieldName = 'user_id';
protected $_eventPrefix = 'cutehits_custom_users_collection';
protected $_eventObject = 'customusers_collection';

/**
* Define resource model
*
* @return void
*/
protected function _construct()
{
$this-&gt;_init('Cutehits\First\Model\Customuser', 'Cutehits\First\Model\ResourceModel\Customuser');
}

/**
* Get SQL for get record count.
* Extra GROUP BY strip added.
*
* @return \Magento\Framework\DB\Select
*/
public function getSelectCountSql()
{
$countSelect = parent::getSelectCountSql();
$countSelect-&gt;reset(\Zend_Db_Select::GROUP);
return $countSelect;
}
/**
* @param string $valueField
* @param string $labelField
* @param array $additional
* @return array
*/
protected function _toOptionArray($valueField = 'user_id', $labelField = 'name', $additional = [])
{
return parent::_toOptionArray($valueField, $labelField, $additional);
}
}

Related posts:

The following two tabs change content below.

Chandra Shekhar

Consultant at Infogain
Chandra Shekhar is a LAMP Developer,Thinker,Blogger and currently working as Magento(Ecommerce) specialist.. I am always open to learn new things in LAMP as well as other newer technology. In the journey of my last 9 years of web and product development, I have decided to share my knowledge and experience to Open Source Community in 2011. In this regard I have started CuteHits.com. Since then I am actively sharing my knowledge on various LAMP technology through CuteHits.com’s technical ... Read More about Chandra Shekhar

Latest posts by Chandra Shekhar (see all)