Problem/Motivation

Add object that uses the FactoryInterface should have dependencies inject via ::create and not ::__construct(). This allows parent classes to change their constructor with breaking any code.
@see https://events.drupal.org/seattle2019/sessions/drupal-9-coming-getting-y...

Example: \Drupal\config_sync\Controller\ConfigSyncController::create
@see https://www.youtube.com/watch?time_continue=1554&v=hN9KjaBvAUk
@see https://www.previousnext.com.au/blog/safely-extending-drupal-8-plugin-cl...

Proposed resolution

Fix subclassing and stop overriding constructors.

Comments

thalles created an issue. See original summary.

thalles’s picture

Status: Needs work » Needs review
StatusFileSize
new3.58 KB

Follow a patch.

thalles’s picture

berdir’s picture

Status: Needs review » Needs work
+++ b/src/Plugin/migrate/source/PathautoPattern.php
@@ -27,27 +27,15 @@ class PathautoPattern extends DrupalSqlBase {
    */
   public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration = NULL) {
-    return new static(
-      $configuration,
-      $plugin_id,
-      $plugin_definition,
-      $migration,
-      $container->get('state'),
-      $container->get('entity_type.manager'),
-      $container->get('entity_type.bundle.info')
-    );
+    /** @var \Drupal\pathauto\Plugin\migrate\source\PathautoPattern */
+    $instance = parent::create($container, $configuration, $plugin_id, $plugin_definition, $migration);
+    $instance->entityTypeBundleInfo = $container->get('entity_type.bundle.info');
+
+    return $instance;

per discussion in the other issue, /** @var static $instance */ usually works fine for me, and this is definitely not valid because it's missing the variable name which is required for an inline definition.

thalles’s picture

I tested it again now and it works for me, so I saw that yesterday's docblock in your comment has a "." after the variable, so it didn't work.

thalles’s picture

Do you want a new patch or you will fix before commit?

thalles’s picture

Status: Needs work » Needs review
StatusFileSize
new5.08 KB

Follow a new patch

mably’s picture

Status: Needs review » Closed (won't fix)

Looks like subclassing is still better for DI and should be prefered when possible.

Check related issue for more details: #3134914: Update FormBase documentation to discourage abuse of create method

Now that this issue is closed, review the contribution record.

As a contributor, attribute any organization that helped you, or if you volunteered your own time.

Maintainers, credit people who helped resolve this issue.