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?