Magento 2 Create Model

Create Model in Magento 2 is a huge path of MVC architecture. In Magento 2 CRUD, models have many different functions such as manage data, install or upgrade module. In this tutorial, I only talk about data management CRUD. We have to create Model, Resource Model, Resource Model Conllection to manage data in table: mageplaza_topic as I mentioned above.

Before create model, we need to create the interface for it. Let create the TopicInterface:


And put this content:

namespace Mageplaza\HelloWorld\Model\Api\Data;
interface TopicInterface
	public function getId();
	public function setId();
	public function getTitle();
	public function setTitle();
	public function getContent();
	public function setContent();
	public function getCreationTime();
	public function setCreationTime();

This interface has defined the set and get method to table data which we would use when interacting with the model. This interface plays an important role when it comes time to exporting CRUD models to Magento service contracts based API.

Now we will create the model file:


And this is the content of that file:

namespace Mageplaza\HelloWorld\Model;
class Topic extends \Magento\Framework\Model\AbstractModel implements \Magento\Framework\DataObject\IdentityInterface,
	const CACHE_TAG = 'mageplaza_topic';

	protected function _construct()

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

This model class will extends AbstractModel class Magento\Framework\Model\AbstractModel and implements TopicInterface and IdentityInterface \Magento\Framework\DataObject\IdentityInterface. The IdentityInterface will force Model class define the getIdentities() method which will return a unique id for the model. You must only use this interface if your model required cache refresh after database operation and render information to the frontend page.

The _construct() method will be called whenever a model is instantiated. Every CRUD model have to use the _construct() method to call _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 Mageplaza\Topic\Model\ResourceModel\Topic The last thing about model 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

Enjoyed the tutorial? Spread it to your friends!


Comments for Magento 2 Create Model

Please leave comments if you have any questions, feedbacks.

You also may like these Magento 2 Extensions

One Step Checkout

10 reviews

Layered Navigation

12 reviews


6 reviews


3 reviews


10 reviews

Zoho CRM

3 reviews

Store Locator

1 review

Better Blog

8 reviews