1

I have been trying to access craft\commerce\services\Gateways; from a plugin but I can't figure out how I need to access it. I've used the following:

$gateways = Commerce::getInstance()->commerce->getAllGateways();

$gateways = craft\commerce\services\Gateways::getAllGateways();

The first one says Getting unknown property: craft\commerce\Plugin::commerce and the second one tells me Non-static method craft\commerce\services\Gateways::getAllGateways() should not be called statically

Can anyone tell me the proper way of doing this? Thanks!

0

Figured it out:

use craft\commerce\Plugin as Commerce;


$gatewayService = Commerce::getInstance()->getGateways();
$variables = [
    'gateways' => $gatewayService->getAllGateways(),
];
| improve this answer | |
  • 1
    FYI: This pattern is a product of Plugins being "singleton" classes, and their instances having Services attached as components, sometimes with special "getter" methods (i.e. ->getGateways()). In most Plugins, it's safe to try MyPlugin::getInstance()->serviceName->methodName(); – August Miller Jan 8 at 20:21
  • So, this probably would have worked as well and I just didn't think of it? $gateways = Commerce::getInstance()->commerce->getGateways()->getAllGateways();? – Darryl Hardin Jan 8 at 21:42
  • 1
    No, you've already got a reference to the plugin instance from Commerce::getInstance()—the commerce property wouldn't exist. Just Commerce::getInstance()->getGateways()->getAllGateways() will do! You might be thinking of the way you get access to Commerce services via Twig ({% set gateways = craft.commerce.gateways.getAllGateways() %}, but this is specific to the templating environment (craft is just a variable that you can hang functionality on, and a lot of plugins attach their singleton instance there). – August Miller Jan 9 at 3:25

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.