2

I wish someone could help me understand this code statement found on the core cRON service (\Drupal\Core\Cron), especially in the constructor method for this class.

public function __construct(ModuleHandlerInterface $module_handler, LockBackendInterface $lock, QueueFactory $queue_factory, StateInterface $state, AccountSwitcherInterface $account_switcher, LoggerInterface $logger, QueueWorkerManagerInterface $queue_manager, TimeInterface $time = NULL) {
  // Omissis
  $this->time = $time ?: \Drupal::service('datetime.time');
}

What does this line do? Why isn't $this->time = $time; instead used?

The service is already injected using arguments.

class: Drupal\Core\Cron
arguments:
  - '@module_handler'
  - '@lock'
  - '@queue'
  - '@state'
  - '@account_switcher'
  - '@logger.channel.cron'
  - '@plugin.manager.queue_worker'
  - '@datetime.time'
lazy: true
0

1 Answer 1

3

It's backward compatibility.

Strictly speaking, constructors are excluded from BC, but the reality is that it is fairly common that one has to override them to inject additional dependencies.

The fallback to the global service means that if such a child class calls the constructor without that argument, it is not going to fatal.

That's especially common for base classes like ContentEntityForm, ControllerBase and other base classes that are specifically designed to be subclassed.

It can also be helpful during updating from an old version, because when running update.php in the UI, the class might be instantiated before Drupal has a chance to rebuild the container and provide the new arguments.

3
  • 1
    Why that one service specifically, though? The cron service injects module handler, lock, queue, state and a bunch of others...what's special about the time service? Is it literally that datetime.time was added as a dependency later?
    – Clive
    Apr 25, 2018 at 9:02
  • 3
    Yes, exactly. The other services were I think there since 8.0, while the time service was added last october, so it is new in Drupal 8.5.
    – Berdir
    Apr 25, 2018 at 9:09
  • Makes sense, cheers
    – Clive
    Apr 25, 2018 at 9:12

Your Answer

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

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