Magento 2 uninstall module
-
13-12-2019 - |
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.
- adds a table called
testing_demo
. So I need to drop it. - adds a product attribute called
demo
. So this needs to be removed - has some settings in
system->configuration
that might or might not be stored in the tablecore_config_data
. All these settings have the pathtesting_demo/...
. So these need to be removed also.
How should my module uninstall script look like?
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:
- Your module should contain an
Uninstall
class at{module}\Setup\Uninstall.php
. - This class should implement
Magento\Framework\Setup\UninstallInterface
. - This class should have an
uninstall
method containing any necessary logic. - 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()
.