3

In Craft 2, we used to be able to do so by doing:

craft()->plugin1->myMethod();

from Plugin 2's service for example.

Now in Craft 3, I couldn't figure out a way to do it.

Plugin1::$plugin->myService->myMethod();

seems to only work within the Plugin 1's code base.

1
  • It works as well in other plugins if they have a variable called $plugin maybe you could tell us the name of the other plugin? Also it's important where you call this method. If it's in your plugins init function chances are high the other plugin is not created at this time Commented Feb 15, 2019 at 6:17

1 Answer 1

4

Assuming Plugin1 is their main plugin class file name, you could do:

\fully\qualified\namespace\Plugin1::getInstance()->myService->myMethod();

In order for this to work:

  1. Craft must be installed.
  2. Plugin1 must be installed and enabled in Craft.
  3. Composer autoloading has to be working so that it knows where to find Plugin1

If you're doing this from a custom module, then you'll need to listen for the EVENT_INIT event, because plugins get instantiated after modules.

i.e.

Craft::$app->on(Application::EVENT_INIT, function() {
    \fully\qualified\namespace\Plugin1::getInstance()->myService->myMethod();
});
4
  • Thanks Brad, exactly what I was looking for.
    – Wei
    Commented Feb 18, 2019 at 0:52
  • 3
    Doing this returns null on getInstance() on my end. Could it be because my plugin class name is called Plugin and I need to name it something else?
    – biko
    Commented Dec 13, 2019 at 3:19
  • Did you figure this out biko? I have the same issue. Commented Jan 7, 2020 at 21:06
  • I have the same issue as Biko, i'm losing my mind over this
    – Kevon
    Commented Oct 23, 2020 at 17:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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