Schema and data patches Magento 2

Patches in Magento 2 are classes containing schema and data manipulation instructions.

Schema and data patches will only be applied once unlike the declarative schema approach. A list of applied patches is stored in the patch_list database table. An unapplied patch will be applied when running the setup:upgrade command.

A data patch is a class that contains data modification instructions.

Data patch is defined in <Vendor>/<Module_Name>/Setup/Patch/Data/<Patch_Name>.php file and implements MagentoFrameworkSetupPatchDataPatchInterface.

A schema patch contains custom schema modification instructions. These modifications can be complex. It is defined in <Vendor>/<Module_Name>/Setup/Patch/Schema/<Patch_Name>.php file and implements MagentoFrameworkSetupPatchSchemaPatchInterface.

Searching for an experienced
Magento 2 Company ?
Read More


You can add dependencies in patches to handle the sequencing of the patches.

To define dependencies in patches you can add the getDependencies() this function to your patch.

Data patch example class:

<?php

namespace WebkulModuleSetupPatchData;

use MagentoFrameworkSetupModuleDataSetupInterface;
use MagentoFrameworkSetupPatchDataPatchInterface;
use MagentoFrameworkSetupPatchPatchRevertableInterface;

class DemoPatch implements DataPatchInterface
{
    /**
     * @var ModuleDataSetupInterface
     */
    private $moduleDataSetup;

    /**
     * @param ModuleDataSetupInterface $moduleDataSetup
     */

    public function __construct(
        ModuleDataSetupInterface $moduleDataSetup
    ) {
        $this->moduleDataSetup = $moduleDataSetup;
    }

    /**
     * @inheritdoc
     */
    public function apply()
    {
        $this->moduleDataSetup->getConnection()->startSetup();
        //The code that you want apply in the patch
        $this->moduleDataSetup->getConnection()->endSetup();
    }

    /**
     * @inheritdoc
     */
    public static function getDependencies()
    {
        return [
            SomeDependency::class
        ];
    }

    /**
     * @inheritdoc
     */
    public function getAliases()
    {
        /**
         * This internal method, that means that some patches with time can change their names,
         */
        return [];
    }
}

You can also check our other blogs https://webkul.com/blog/what-is-page-builder-in-magento-2/

Magento 2 doc https://developer.adobe.com/commerce/php/development/components/declarative-schema/patches/

Conclusion: We should use a data patch to insert data in the table and a schema patch to create, delete or alter tables. As we discussed above the patches execute only once and on setup:upgrade commands the schema patches execute first and then the data patch. For example, if you have to create a table and then insert some data into it with a patch then you can do it by following this blog. You can also leave a comment if you have any doubts.


Source link