?> tutorial Archives - Addeos

Tag Archive tutorial

Magento 2 – Tutorial : new model – Part 2 – creating the PHP classes

Introduction

This article is the 2nd part of a series in which I go through the procedure to create a new model in magento 2, with its own magento 2 admin grid in the Back Office.

You can go back to the first part if you wish.

As a preamble, I have to say that this tutorial series has been developed and tested with Magento version 2.4.2.

I remind you that for the purpose of the article I am going to create a "provider" model and that our code will be contained in an "Addeos_ModelTutorial" module.

In the first part I have explained how to create the DB table using declarative XML. In this second part, I will create the PHP classes :

  • the API data interface
  • the model that implements the interface
  • the resource model
  • the collection resource model

Creating the API data interface

If we want to respect the concept of service contracts which is a good thing and recommanded by Magento, I need to create some PHP interfaces first. Here is some more details about service contracts.

By convention, these PHP interfaces have to be in an Api folder and a Data folder for data interfaces.

The first interface to create is the ProviderInterface : Api/Data/ProviderInterface.php.

Here is the code :

<?php

declare(strict_types=1);

namespace Addeos\ModelTutorial\Api\Data;

/**
 * @api
 */
interface ProviderInterface
{
    const ENTITY_ID = 'entity_id';
    const CREATED_AT = 'created_at';
    const UPDATED_AT = 'updated_at';
    const NAME = 'name';
    const DESCRIPTION = 'description';

    public function getEntityId(): ?int;

    public function setEntityId(int $entityId);

    public function getName(): ?string;

    public function setName(string $name);

    public function getDescription(): ?string;

    public function setDescription(string $description);

    public function getCreatedAt(): ?string;

    public function setCreatedAt(string $createdAt);

    public function getUpdatedAt(): ?string;

    public function setUpdatedAt(string $updatedAt);

}

Creating the PHP model

I then need to create the PHP model that will implement the interface we have just created. This PHP class will extend \Magento\Framework\Model\AbstractModel.

Here is the code :

<?php
declare(strict_types=1);

namespace Addeos\ModelTutorial\Model;

use Addeos\ModelTutorial\Api\Data\ProviderInterface;
use Magento\Framework\Model\AbstractModel;

class Provider extends AbstractModel implements ProviderInterface
{

    public function getName(): ?string
    {
        return $this->getData(self::NAME);
    }

    public function setName(string $name)
    {
        $this->setData(self::NAME, $name);
    }

    public function getDescription(): ?string
    {
        return $this->getData(self::DESCRIPTION);
    }

    public function setDescription(string $description)
    {
        $this->setData(self::DESCRIPTION, $description);
    }

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

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

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

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

Creating the resource model

I now need to create resource model.

The file is Model/ResourceModel/Provider.php.

Here is the code :

<?php
declare(strict_types=1);

namespace Addeos\ModelTutorial\Model\ResourceModel;

use Magento\Framework\Model\ResourceModel\Db\AbstractDb;

class Provider extends AbstractDb
{
    protected function _construct()
    {
        $this->_init('addeos_provider', 'entity_id');
    }
}

Creating the collection resource model

I now need to create the provider collection resource model.

The file is ModelResourceModel/Provider/Collection.php.

Her is the code :

<?php

namespace Addeos\ModelTutorial\Model\ResourceModel\Provider;

use Addeos\ModelTutorial\Model\Provider;
use Addeos\ModelTutorial\Model\ResourceModel\Provider as ProviderResourceModel;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;

class Collection extends AbstractCollection
{
    protected $_idFieldName = 'entity_id';
    protected $_eventPrefix = 'addeos_provider_collection';
    protected $_eventObject = 'addeos_provider_collection';

    protected function _construct()
    {
        $this->_init(Provider::class, ProviderResourceModel::class);
    }
}

And that's all. From that point we have all the necessary classes for now.

In next post, I will explain now how to create the grid in Back Office to visualize the data of our new table.

Magento 2 – Tutorial : adding a new model – Part 1 – creating the DB table

Introduction

Here is the first post of a series during which I will got through all the procedure to create a new model in magento 2, with its own grid in the Back Office.

Here are the steps we will have to through :

  1. Creating the DB table
  2. Creating the API data object
  3. Creating the model
  4. Creating the resource model
  5. Creating the collection resource model
  6. Creating the grid

I will cover all these steps in a series of posts.

As a preamble, I have to say that this tutorial series has been developed and tested with Magento version 2.4.2.

For the purpose of the series, we will create a simple model for a "provider" entity with the following columns :

  • id : the provider unique identifier
  • created_at : the date the provider was created
  • updated_at : the date the provider was updated
  • name : the provider name
  • description : the provider description

We will assume that our code will be held in a module Addeos_ModelTutorial.

Creating the table in DB

Rather than using InstallSchema.php file we can now use XML declarative schema definition for creating new tables, or even updating existing tables. This is available since Magento version 2.3.

We will create a db_schema.xml file.

He is the content of the file:

<?xml version="1.0"?>
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
    <table name="addeos_provider" resource="default" engine="innodb" comment="Porviders">
        <column xsi:type="int" name="entity_id" padding="10" unsigned="true" nullable="false" identity="true"
                comment="Entity ID"/>
        <column xsi:type="timestamp" name="created_at" on_update="false" nullable="false" default="CURRENT_TIMESTAMP"
                comment="Created At"/>
        <column xsi:type="timestamp" name="updated_at" on_update="false" nullable="false" default="CURRENT_TIMESTAMP"
                comment="Updated At"/>
        <column xsi:type="varchar" name="name" nullable="true" comment="Name" length="50"/>
        <column xsi:type="varchar" name="description" nullable="true" comment="Description" length="50"/>
        <constraint xsi:type="primary" referenceId="PRIMARY">
            <column name="entity_id"/>
        </constraint>
        <index referenceId="ADDEOS_PROVIDER_ENTITY_ID" indexType="btree">
            <column name="entity_id"/>
        </index>
    </table>
</schema>

More information on declarative schema can be found here.

Once this file is in place, you will simply need to run a setup upgrade command from your magento installation root directory :

bin/magento setup:upgrade --keep-generated

Once this is done, your new table will be present in DB.

And this is all for that first step.

In the next post I explain the different PHP classes we need to create.