Uploaded image for project: 'Moodle'
  1. Moodle
  2. MDL-84912

moodle_database not available for DI in routed classes

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Unresolved
    • Icon: Minor Minor
    • None
    • 4.5.4
    • General
    • None
    • MOODLE_405_STABLE

      It seems that the moodle_database class, that can normally be injected into the constructor of classes obtained through \core\di, is null when the class is used for routing through r.php

      Something like this should reproduce it:

      namespace local_plugin\route\api;
       
      [use statements omitted]
       
      class my_service {
          
          public function __construct(private moodle_database $db) {}
       
          #[route(path:'/some/path')]
          public function execute(ServerRequestInterface $request) {
              $version = $this->db->get_record('config', ['name' => 'version']);
       
              return new payload_response([$version], $request);
          }
      }
      

      The $DB global would still work here as the actual method isn't called until after the moodle_bootstrap_middleware has finished the setup.

      The root of the problem seems to be this line in router::get_route_instance_for_request() which appears to actually instantiate the class. Wrapping this line and the one before it in another if (!is_array($callable)) check makes it behave as expected.

      I'm not at all sure that this is the correct fix (or even that it's definitely a bug), and presumably that would still fail if callable parameter was not already an array. (I haven't been able to figure out if there's a way to reach that code with something that isn't an array - it looks like slim may already have dealt with this for us.)

      If someone can give me a steer on what would be the correct fix for this I'm happy to create a patch for it, but I don't feel I understand it well enough at the moment to do that.

            Unassigned Unassigned
            maherne Michael Aherne
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:

                Error rendering 'clockify-timesheets-time-tracking-reports:timer-sidebar'. Please contact your Jira administrators.