Magento 2 Install Setup Scripts

Setup scripts are a key feature in the Magento application. They provide the ability for a developer to add, update or remove data from the database using PHP classes. This guide will focus on how to add Magento 2 install setup scripts.

Let’s add a new module to start with called ‘Siphor_Names’. Start with the module.xml file.

// app/code/Siphor/Names/etc/module.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Siphor_Names" setup_version="1.0.0" />
</config>

Then add the module’s registration.php file.

// app/code/Siphor/Names/registration.php
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Siphor_Names',
    __DIR__
);

There are a few classes that should be added when using setup scripts. A model class, a resource model to perform the CRUD operations on the database, and a collection class to retrieve the data and to provide the ability to manipulate it.

Models should belong in the ‘Model’ directory of the module structure. Let’s add one now.

// app/code/Siphor/Names/Model/Names.php
<?php
namespace Siphor\Names\Model;

class Names extends \Magento\Framework\Model\AbstractModel
    implements \Magento\Framework\DataObject\IdentityInterface
{

    const CACHE_TAG = 'siphor_names_names';

    protected function _construct()
    {
        $this->_init('Siphor\Names\Model\ResourceModel\Names');
    }

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

Similar to Magento 1, Magento 2 models also extend a core Magento class. In this case, it’s \Magento\Framework\Model\AbstractModel.

You’ll also notice that the model class implements \Magento\Framework\DataObject\IdentityInterface. This is so that you define the getIdentities() method, which is used for caching purposes.

Within the _construct() method, pass in the resource model class name as the argument within the _init() method.

The resource model will then be added within the specified directory. The resource models extend the \Magento\Framework\Model\ResourceModel\Db\AbstractDb core class.

// app/code/Siphor/Names/Model/ResourceModel/Names.php
<?php
namespace Siphor\Names\Model\ResourceModel;

class Names extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{
    protected function _construct()
    {
        $this->_init('siphor_names', 'name_id');
    }
}

Within this class’ _init() method, the name of your table to add to the database and the ID field name are the arguments passed in.

Now for the collection class, which should extend \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection.

Within the collection’s _init() method, the model class name and resource model class names are passed in as strings.

// app/code/Siphor/Names/Model/ResourceModel/Names/Collection.php
<?php
namespace Siphor\Names\Model\ResourceModel\Names;

class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
    protected function _construct()
    {
        $this->_init('Siphor\Names\Model\Names','Siphor\Names\Model\ResourceModel\Names');
    }
}

Finally, it’s time for the install script. Magento now does not use files which contain version names (e.g. install-1.0.0.php). Instead, we have Schema setup classes.

  • Setup/InstallSchema
  • Setup/UpgradeSchema
  • Setup/InstallData
  • Setup/UpgradeData
  • Setup/Recurring
  • Setup/Uninstall

This article will look at the InstallSchema class, which is responsible for adding the table its columns to the database.

You may be familiar with Magento’s DDL classes to add information to the database. These classes are used again in the current versions of Magento.

In the below example, the ‘name_id’, ‘name’ and ‘description’ columns are added.

// app/code/Siphor/Names/Setup/InstallSchema.php
<?php
namespace Siphor\Names\Setup;

use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\DB\Ddl\Table;

class InstallSchema implements InstallSchemaInterface
{
    public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $installer = $setup;
        $installer->startSetup();
        $tableName = $installer->getTable('siphor_names');

        if ($installer->getConnection()->isTableExists($tableName) != true) {
            $table = $installer->getConnection()
                ->newTable($tableName)
                ->addColumn(
                    'name_id',
                    Table::TYPE_INTEGER,
                    null,
                    [
                        'identity' => true,
                        'unsigned' => true,
                        'nullable' => false,
                        'primary' => true
                    ],
                    'ID'
                )
                ->addColumn(
                    'name',
                    Table::TYPE_TEXT,
                    255,
                    ['nullable' => false, 'default' => ''],
                    'Title'
                )
                ->addColumn(
                    'description',
                    Table::TYPE_TEXT,
                    255,
                    ['nullable' => false, 'default' => ''],
                    'Description'
                );
            $installer->getConnection()->createTable($table);
        }
        $installer->endSetup();
    }
}

Then, run the following commands to enable the module and upgrade the database.

$ /path/to/your/php bin/magento module:enable --clear-static-content Siphor_Names
$ /path/to/your/php bin/magento setup:upgrade

This will add the module to the ‘setup_module’ in the database, and of course the ‘siphor_names’ table will be added along with the three columns created.

Magento 2 Install Setup Scripts

Magento 2 Install Setup Scripts

Note: This article is based on Magento CE version 2.1.