Quantcast
Channel: Issues for Drupal core
Viewing all articles
Browse latest Browse all 295716

[policy, no patch] Reduce code reuse in dependency injection

$
0
0

Problem/Motivation

When using dependency injection to add services to classes, it is not difficult to quickly add a large number of arguments, which then must be replicated on every class that extends this one, leading to method declarations that are hundreds of characters long. In addition, the create method must be recreated verbatim from the parent class and then have new services added to it, creating code reuse and potential errors should the parent class add or remove a service.

Using the following regex on core, I found 107 examples of classes that are injecting 5 or more classes.
/public function __construct\(([A-Z][^,)]*,[^,)A-Z]*){6}/

Proposed resolution

My idea to get around the issues with the create() method is to add a preCreate($container) (maybe getDependencies()?) method that is used like this.

class MyClass {

  public static function create(ContainerInjectionInterface $container) {
    // Get the class that this method is called from.
    $class = static::class;
    // Get the services required by that class.
    $services = $class::preCreate($container);
   
    // Create the object.
    return new static ($configuration, ...$services);
  }

  protected static function preCreate(ContainerInjectionInterface $container) {
    // Get and return services in an array.
    return [
      $container->get('my.service')
    ],
  }

}

From here new classes would simply have to create a new preCreate() method.


class myChildClass extends myClass {
  protected static function preCreate(ContainerInjectionInterface $container) {
  $services = parent::class::preCreate($container);
  $services += [
     // All my new services.
  ];
  
  return $services;
  }
}

This does nothing about the creeping length of the constructor itself, but reduces the amount of repetition in create() methods.

API changes

As demonstrated above, the proposed changes add new syntax in exchange for less repetition. Previous create() methods would continue to work as normal, as they bypass their parent's create() methods entirely. To my knowledge, this changes nothing about how the services are handled outside the classes themselves.


Viewing all articles
Browse latest Browse all 295716

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>