drupal-code-generator icon indicating copy to clipboard operation
drupal-code-generator copied to clipboard

Consider removing DI questions from generators

Open Chi-teck opened this issue 1 year ago • 5 comments

For most services, plugin and controllers DCG asks a user which services he would like to inject.

DCG service question

That allows to save a user form typing a lot of boilerplate code. However times have changed. PHP improved the type system and implemented property promotions. Drupal added support for service auto-wiring.

Here is example of a service in Drupal 8 style. Imagine how it would look if it had say 5 dependencies.

example:
  class: Drupal\example\Example
  arguments: ['@entity_type.manager'
<?php

namespace Drupal\example;

use Drupal\Core\Entity\EntityTypeManagerInterface

/**
 * The example service.
 */
class Example implements ExampleInterface {

  /**
   * The entity type manager service.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The object constructor.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager service.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

}

Here is the same service in Drupal 11 style.

<?php

namespace Drupal\example;

use Drupal\Core\Entity\EntityTypeManagerInterface;

/**
 * The example service.
 */
final class Example implements ExampleInterface {

  /**
   * The object constructor.
   */
  public function __construct(private EntityTypeManagerInterface $entity_type_manager) {  }

}

From the above example seems that asking a user to provide dependencies for a service does not make much sense this times. It can easily add them to the generated code later.

Chi-teck avatar Jun 13 '24 14:06 Chi-teck

There's auto wire now. +1 to not ask

andypost avatar Jun 13 '24 14:06 andypost

I'm neutral on this. A coder has to lookup the service name and type hint - thats not nothing.

This question would benefit a lot from a MultiSearch Prompt. Please consider switching to Laravel Prompts as Drush has done.

weitzman avatar Jun 13 '24 14:06 weitzman

A coder has to lookup the service name and type hint - thats not nothing

That's the main reason to keep these questions.

Chi-teck avatar Jun 13 '24 14:06 Chi-teck

On the other hand generating DI code in DCG is quite complex. It has a very high maintenance cost.

Chi-teck avatar Jun 13 '24 14:06 Chi-teck

There are a few open issues related to services. I think we should wait for them to be resolved.

  • https://www.drupal.org/project/drupal/issues/3422359
  • https://www.drupal.org/project/drupal/issues/3294266
  • https://www.drupal.org/project/drupal/issues/3296391
  • https://www.drupal.org/project/drupal/issues/3452852

Chi-teck avatar Jun 15 '24 05:06 Chi-teck