I am creating a module and I am progressing it. I am new to Magento 2 so there are a lot of things that I am not yet familiar too. As a module creator, I am curious how to run an uninstall script when someone uninstalled your module via command line.
I know I can execute the module uninstall command like this:
php bin/magento module:uninstall -r Vendor_Module
Best Answer
Magento Setup Uninstall script
The below page in the Magento DevDocs explains the process of module uninstallation. It explains the steps that are taken and one of those steps is running Uninstall scripts of the modules:
http://devdocs.magento.com/guides/v2.2/install-gde/install/cli/install-cli-uninstall-mods.html#instgde-cli-uninst-mod-uninst
So this indicates for a module to run a script at uninstall, the module should be uninstalled using the
--remove-data
option, or shorthand-r
. So if the users of your module do not use that option, the script won't run.For a "Company MyModule" module, the script should be located at
app/code/Company/MyModule/Setup/Uninstall.php
orvendor/company/mymodule/Setup/Uninstall.php
and must implement the\Magento\Framework\Setup\UninstallInterface
interface. It could look like this:Composer Package Uninstall event script
If your module is a composer package (residing in
vendor/
), then the Magento module uninstaller will runcomposer remove
to remove the package files that were installed into thevendor
dir.Now, composer has a mechanism to run scripts on certain events, including package removal/uninstall. Unfortunately for module vendors, only scripts configured in the root
composer.json
will be ran. So if you have scripts configured like below in your rootcomposer.json
(root of your Magento project), then these will be triggered whenever a module will be uninstalled through the Magentobin/magento module:uninstall
command:https://getcomposer.org/doc/articles/scripts.md