Magento 2- Helloworld – Add new table and access using model

In this blogpost we will focus on to create a new table and add some data into it. Then we will be saving some data to table and will get the data using model class. We will be covering:-

Setup file
Models
Resource Models
Collection Models

Step 1

We will first create setup file, Magento 2 has installSchema.php file, which is executed on installation of module and is responsible for schema related modification in database. There is no version related concept in Magento2 for setup files as it was in Magento 1.
In our setup script we will be creating a table ‘w3solver_helloworld’ which has following field:-

Id
Title
Created At
Updated At
W3solver\Helloworld\Setup
<?php

namespace W3solver\Helloworld\Setup;

class InstallSchema implements \Magento\Framework\Setup\InstallSchemaInterface {

    public function install(\Magento\Framework\Setup\SchemaSetupInterface $setup, \Magento\Framework\Setup\ModuleContextInterface $context) {

        $installer = $setup;
        $installer->startSetup();

        $table = $installer->getConnection()->newTable(
                                $installer->getTable('w3solver_helloworld')
                        )->addColumn(
                                'id', \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, null, [ 'identity' => true, 'nullable' => false, 'primary' => true, 'unsigned' => true,], 'ID')
                        ->addColumn(
                                'title', \Magento\Framework\DB\Ddl\Table::TYPE_TEXT, 255, [ 'nullable' => false,], 'Title')
                        ->addColumn(
                                'created_at', \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP, null, [ 'nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT,], 'Created At'
                        )->addColumn(
                'updated_at', \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP, null, [ 'nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT_UPDATE,], 'Updated At'
        );
        $installer->getConnection()->createTable($table);

        $installer->endSetup();
    }

}

You need to execute setup:upgrade command to see the table in database. If even after running the command table is not created then you need to review setup_module table and execute the following sql

DELETE from setup_module where module = 'W3solver_Helloworld';

Step 2

Now we have got the table definition installed, lets take a look at CRUD Model files.
We will be covering about four files:-

W3solver/Helloworld/Model/Hello.php
W3solver/Helloworld/Model/ResourceModel/Hello.php
W3solver/Helloworld/Model/ResourceModel/Hello/Collection.php
W3solver/Helloworld/Model/HelloInterface.php

Firstly lets create a base model:-

<?php

namespace W3solver\Helloworld\Model;

class Hello extends \Magento\Framework\Model\AbstractModel implements HelloInterface, \Magento\Framework\DataObject\IdentityInterface
{
    const CACHE_TAG = 'w3solver_helloworld';
 
    protected function _construct()
    {
        $this->_init('W3solver\Helloworld\Model\ResourceModel\Hello');
    }
 
    public function getIdentities()
    {
        return [self::CACHE_TAG . '_' . $this->getId()];
    }
    
    public function getId()
    {
        return $this->getData(self::ID);
    }

    public function getTitle()
    {
        return $this->getData(self::TITLE);
    }

    public function getCreatedAt()
    {
        return $this->getData(self::CREATED_AT);
    }

    public function getUpdatedAt()
    {
        return $this->getData(self::UPDATED_AT);
    }

    public function setId($id)
    {
        return $this->setData(self::ID, $id);
    }

    public function setTitle($title)
    {
        return $this->setData(self::TITLE, $title);
    }

    public function setCreatedAt($created_at)
    {
        return $this->setData(self::CREATED_AT, $created_at);
    }

    public function setUpdatedAt($updated_at)
    {
        return $this->setData(self::UPDATED_AT, $updated_at);
    }

}
?>

All Magento CRUD model extends

 Magento\Framework\Model\AbstractModel

And as you have seen that this model is implementing HelloInterface and IdentityInterface. IdentityInterface forces developer to implement a getidentities function

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

This interface is basically used for model which require cache refresh after CRUD operations. Method getIdentities will return a unique id for each instance of this model, which is cacheable.
Apart from this model class has also implemented HelloInterface. Magento 2 strongly recommends to use PHP Interfaces, Interface plays important role when we use service contracts based API. So we will be creating an interface for our model. We will be adding all getter and method in the interface.

W3solver\Helloworld\Model\HelloInterface
<?php
namespace W3solver\Helloworld\Model;

interface HelloInterface
{
    const ID     = 'id';
    const TITLE    = 'title';
    const CREATED_AT = 'created_at';
    const UPDATED_AT   = 'updated_at';
    
    public function getId();

    public function getTitle();

    public function getCreatedAt();

    public function getUpdatedAt();

    public function setId($id);

    public function setTitle($title);

    public function setCreatedAt($createdAt);

    public function setUpdatedAt($updatedAt);

}

Step 3

Model mainly contain the overall database logic but actual sql queries get executed using resource model. So lets have our resource model

W3solver\Helloworld\Model\ResourceModel\Hello.php
<?php

namespace W3solver\Helloworld\Model\ResourceModel;

class Hello extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb {

    protected $_date;

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

    protected function _construct() {
        $this->_init('w3solver_helloworld', 'id');
    }

    protected function _beforeSave(\Magento\Framework\Model\AbstractModel $object) {

        if ($object->isObjectNew() && !$object->hasCreatedAt()) {
            $object->setCreatedAt($this->_date->gmtDate());
        }

        $object->setUpdatedAt($this->_date->gmtDate());

        return parent::_beforeSave($object);
    }

}

Collection

W3solver\Helloworld\Model\ResourceModel\Hello\Collection.php
<?php 
namespace W3solver\Helloworld\Model\ResourceModel\Hello;

class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
    /**
     * @var string
     */
    protected $_idFieldName = 'id';

    /**
     * Define resource model
     *
     * @return void
     */
    protected function _construct()
    {
        $this->_init('W3solver\Helloworld\Model\Hello', 'W3solver\Helloworld\Model\ResourceModel\Hello');
    }

}

Step 4

Now we will be changing our block file to get the text value from table/model.

<?php

namespace W3solver\Helloworld\Block;

class Hello extends \Magento\Framework\View\Element\Template {

    protected $_helloModelFactory;
    
    public function __construct(
    \Magento\Framework\View\Element\Template\Context $context,
    \W3solver\Helloworld\Model\HelloFactory $helloModelFactory
    ) {
        $this->_helloModelFactory = $helloModelFactory;
        parent::__construct($context);
    }

    protected function _prepareLayout()
    {
/* Since our table is just created so here we are first making an entry in database*/
        $test = $this->_helloModelFactory->create();
        $test->setTitle('Hello World');
        $test->save();
        $this->setText($test->getData('title'));
    }
}

Leave a Comment.