2

I'm always using this way of injecting service to controller:

<?php    
namespace Drupal\TestModule\Controller;
    
    use Drupal\Core\Controller\ControllerBase;
    use Symfony\Component\DependencyInjection\ContainerInterface;
    
    class TestModuleController extends ControllerBase {
    
      protected $testModule;
    
        public function __construct(TestModule $testModule) {
        $this->testModule = $testModule;
      }
    
      public static function create(ContainerInterface $container) {
        return new static(
          $container->get('testModule.service')
        );
      }
    
      public function testModule() {
        return [
          '#type' => 'markup',
          '#markup' => $this->testModule->getTestModule(),
        ];
      }
    }

But with drupal console I generate Controller with service (drupal gcon command) and get different code:

<?php
    namespace Drupal\TestModule\Controller;
    
    use Drupal\Core\Controller\ControllerBase;
    use Symfony\Component\DependencyInjection\ContainerInterface;
    
    class TestModuleController extends ControllerBase {
    
      protected $testModule;
    
      public static function create(ContainerInterface $container) {
        $instance = parent::create($container);
        $instance->testModule = $container->get('testModule.service');
        return $instance;
      }
    
      public function testModule() {
        return [
          '#type' => 'markup',
          '#markup' => $this->testModule->getTestModule(),
        ];
      }
    }

Is this second way better than first and which should I use?

1 Answer 1

3

TL;DR: The second way is better.

The constructor method __construct() is considered internal, you can not (savely) overwrite it. E.g. the number or type of mandatory function parameters might change. Therefore the first version's code might break even within a minor update of Drupal core. Only the second version is guaranteed to work at least until the next major version release.

For more information I'd suggest reading this Change record from the Webform module.

2

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.