What are Setup Scripts in Magento 2 and why you should use them

13 Jun 2019
Setup Scripts

So you have created your first Magento 2 module.

You have created the registration.php, the module.xml, everything. You have taken good care to see that your code quality is good and you have put comments for every single class and function you’ve developed. Sounds like a perfect module right? One small catch.

Your module requires a table to be created in the database, let’s say “my_first_module_table”. And it has four columns.

Now, whoever downloads your module, and installs it into their Magento installation, has to create that table, having the exact same schema, for your module to work properly. Seems kind of a headache right? So what do you do?

Don’t worry. You don’t have to go to every single client of yours to run the “CREATE TABLE” mySQL command at their system. Magento has provided a way for the modules that you create to modify the schema of the Magento database.

Setup Scripts

Setup scripts are certain classes inside your module which are executed, either once, or whenever your module version is updated. Setup scripts in Magento 2 database configuration files that modify the Magento installation. They are usually used for database configuration but can be used for many other things.Magento supports 4 kinds of setup scripts

InstallSchema 

Run once per module. Used to add new tables or modify existing table architecture in the database. Implements the Magento\Framework\Setup\InstallSchemaInterface

InstallData

 Run once per module. Used to add/edit/delete records (rows) from existing tables in the database. Implements the Magento\Framework\Setup\InstallDataInterface.

UpgradeSchema

Runs everytime the module version changes. Used to add new tables or modify existing table architecture in the database. Implements the Magento\Framework\Setup\UpgradeSchemaInterface.

UpgradeData

Runs everytime the module version changes. Used to add/edit/delete records (rows) from existing tables in the database. Implements the Magento\Framework\Setup\UpgradeDataInterface.

So coming back to our above example, we could probably create an InstallSchemain our module, and create our table in that class.

<?php
/**
 *
 * @package     magento2
 * @author      Jayanka Ghosh
 * @license     https://opensource.org/licenses/OSL-3.0 Open Software License v. 3.0 (OSL-3.0)
 * @link        https://www.codilar.com/
 */

namespace Jayanka\HelloWorld\Setup;


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

class InstallSchema implements InstallSchemaInterface
{

    /**
     * Installs DB schema for a module
     *
     * @param SchemaSetupInterface $setup
     * @param ModuleContextInterface $context
     * @return void
     */
    public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $this->createMyTable($setup);
    }

    protected function createMyTable(SchemaSetupInterface $setup) {
        $tableName = $setup->getTable("my_first_module_table");
        $table = $setup->getConnection()->newTable(
            $tableName
        )->addColumn(
            'id',
            Table::TYPE_INTEGER,
            null,
            ['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
            'entity_id'
        )->addColumn(
            'name',
            Table::TYPE_TEXT,
            100,
            ['nullable' => false]
        )->addColumn(
            'description',
            Table::TYPE_TEXT,
            255,
            ['nullable' => false]
        )->addColumn(
            'created_at',
            Table::TYPE_TIMESTAMP,
            null,
            ['nullable' => false, 'default' => Table::TIMESTAMP_INIT],
            'Create date'
        )->setComment(
            'My first module table'
        );
        $setup->getConnection()->createTable($table);
    }
}

That’s all on setup scripts. You can use the same concept to create new tables, or update existing tables, or even add data into existing tables (like creating a product attribute which you need in your module).

Do you want us to make a blog post tutorial on a particular Magento topic? Comment the topic in the comment section below. See you till next time!

Was this article helpful?
Jayanka Ghosh

Jayanka Ghosh

Experienced Magento Developer with a proven track record in the IT and services industry, specializing in PHP, Magento, HTML, jQuery, CSS, and E-commerce.

Our Offices Are Here

India flag

India

7th Floor, Jupiter Block Prestige Tech Park, Kadubeesanahalli, Bellandur Amtankere, Bengaluru, Karnataka 560103

+91 888 49 00 505

UAE flag

UAE

DTECH, Techno Hub 1, Dubai Silicon Oasis Authority, United Arab Emirates - Dubai - United Arab Emirates

+971 55 557 8583

Saudi Arabia flag

Saudi Arabia

Building No 6827, Prince Turki Ibn Abdulaziz Al Awal Street, Al Muhammadiyah District, Riyadh, Kingdom of Saudi Arabia- 12362

+966 50 809 6356

Oman flag

Oman

Building No. 2/786, Way No. 43, Block No. 336, Al Khud 132, Muscat, Oman

+968 7694 6200

Singapore flag

Singapore

Codilar Digital Pte Ltd, 68 Circular Road, #02-01, 049422, Singapore

Indonesia flag

Indonesia

Satrio Tower, Floor 6, Unit C and D, Desa/Kelurahan Kuningan Timur, Kec. Setiabudi, Kota Adm. Jakarta Selatan, Provinsi DKI Jakarta

CONTACT US

Let's Do Something Great Together

We look forward to hearing from you

REGIONS

KSA|UAE|OMAN|INDIA|SINGAPORE|INDONESIA