Question

Apparently, now Magento 2 supports uninstall scripts that allow db schema modification when uninstalling a module (horay!!).
As explained in here this only works for module installed via composer.
(I hope it will work in the future for all modules, but that's a different issue).
Let's say I have a module called Testing_Demo.
This module does 3 things that I would like to be removed when uninstalling it.

  1. adds a table called testing_demo. So I need to drop it.
  2. adds a product attribute called demo. So this needs to be removed
  3. has some settings in system->configuration that might or might not be stored in the table core_config_data. All these settings have the path testing_demo/.... So these need to be removed also.

How should my module uninstall script look like?

Was it helpful?

Solution

Searching the codebase for UninstallInterface gives \Magento\Setup\Model\UninstallCollector.

If you search for UninstallCollector then, you'll find that's used in \Magento\Setup\Console\Command\ModuleUninstallCommand. Particularly relevant:

    $uninstalls = $this->collector->collectUninstall();
    $setupModel = $this->objectManager->get('Magento\Setup\Module\Setup');
    foreach ($modules as $module) {
        if (isset($uninstalls[$module])) {
            $output->writeln("<info>Removing data of $module</info>");
            $uninstalls[$module]->uninstall(
                $setupModel,
                new ModuleContext($this->moduleResource->getDbVersion($module) ?: '')
            );
        } else {
            $output->writeln("<info>No data to clear in $module</info>");
        }
    }

Put together, we can surmise:

  1. Your module should contain an Uninstall class at {module}\Setup\Uninstall.php.
  2. This class should implement Magento\Framework\Setup\UninstallInterface.
  3. This class should have an uninstall method containing any necessary logic.
  4. The same objects and methods are available to you as in any setup or upgrade script.

So, here's your skeleton:

<?php

namespace \Custom\Module\Setup;

class Uninstall implements \Magento\Framework\Setup\UninstallInterface
{
    /**
     * Module uninstall code
     *
     * @param \Magento\Framework\Setup\SchemaSetupInterface $setup
     * @param \Magento\Framework\Setup\ModuleContextInterface $context
     * @return void
     */
    public function uninstall(
        \Magento\Framework\Setup\SchemaSetupInterface $setup,
        \Magento\Framework\Setup\ModuleContextInterface $context
    ) {
        $setup->startSetup();

        // Uninstall logic here

        $setup->endSetup();
    }
}

Remove any tables, columns, or data using the appropriate methods. See \Magento\Framework\DB\Adapter\AdapterInterface, available as $setup->getConnection().

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top