1

I'm creating a plugin (A) that has optional support for another 3rd party plugin (B). When my plugin A is installed, I create a number of tables. If plugin B is also installed my migrations create further tables specifically for plugin B.

The problem is if someone installs plugin A, then only installs plugin B afterward, my custom tables are never created.

How can I create tables/run migrations only when a plugin (B) is installed?

EDIT

I've been able to get this working with the following:

Event::on(
  Plugins::class,
  Plugins::EVENT_AFTER_INSTALL_PLUGIN,
  function (Event $event) {
    if ($event->plugin->handle == "pluginB") {
      $migration = new migrations\m201031_120401_add_pluginB_support();
      $migration->safeUp();
    }
  });
1

You can have plugin A listen for the EVENT_AFTER_INSTALL_PLUGIN event.

It could then check if $plugin->handle is for plugin B and if so, run any additional install migrations or logic.

You could do something similar for the EVENT_AFTER_UNINSTALL_PLUGIN event to clean things up in the case where one gets uninstalled.

3
  • Thanks Brad, I've got the event listening and handle check now, but not sure on how to run migrations independently? If I try use the $plugin->getMigrator()->migrateUp("name_of_migration") I get an error as that migration has already been run (or at least added to the migration table). – Timmy O'Mahony Nov 17 '20 at 9:11
  • Ah, I'm able to just run the migration and its safeUp method just as a regular class method (see original question update). Is this a sensible approach to running a migration outside of the migrator? Thanks for your help – Timmy O'Mahony Nov 17 '20 at 9:40
  • 1
    Yup, seems reasonable to me. – Brad Bell Nov 17 '20 at 21:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.