Use dependency injection rather than Drupal object

Created on 24 April 2025, 7 days ago

Problem/Motivation

Follow-up from πŸ“Œ Add gitlab ci integration for code standards and eventual tests Active .

There are several phpstan code quality issues that can be resolved. The biggest one is to not use static methods on the Drupal object.

FormBase already implements ContainerInjectionInterface, which allows us to use the static `create method`. It also has some helpful traits and includes requestStack and configFactory as protected members (although not injected).

Pre-existing methods:

  // $config = \Drupal::config('node_swapper.settings')
  $config = $this->configFactory->get('node_swapper.settings');
  // $unpublish = \Drupal::request()->query->get('unpublish', $config->get('old_node_unpublish');
  $unpublish = $this->getRequest()->query->get('unpublish', $config->get('old_node_unpublish');

Injecting dependencies:

  public static function create(ContainerInterface $container) {
    return new static(
      // Replaces \Drupal::database().
      $container->get('database'),
      // Replaces \Drupal::time().
      $container->get('datetime.time'),
      // The static EntityInterface::load calls can be replaced as well.
      $container->get('entity_type.manager'),
     // Replaces \Drupal::service('path_alias.manager').
      $container->get('path_alias.manager'),
    );
  }

  // Example using PHP 8 code.
  public function __construct(protected $database, protected $time, protected $entityTypeManager, protected $pathAliasManager) { }

Additionally we can be even cleaner, if we inject the dependencies for requestStack, configFactory, and messenger, using the setter methods

Proposed resolution

Remove use of \Drupal in forms by implementing the static create method and the __construct initialization method assigning the services to protected variables either via existing FormBase methods or via manual assignment.

This would make it easier to mock those dependencies in a Kernel test or pure unit test later.

Remaining tasks

User interface changes

No.

API changes

The classes are final so it doesn't matter.

Data model changes

No.

πŸ“Œ Task
Status

Active

Version

1.1

Component

Code

Created by

πŸ‡ΊπŸ‡ΈUnited States mradcliffe USA

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024