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
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.

| improve this answer | |
  • 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 '18 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 '18 at 9:09
  • Makes sense, cheers – Clive Apr 25 '18 at 9:12

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.