2

i have a class

Paybox

This class is declare as a service.

In my controller class, i inject this service like this :

public function __construct($payboxService) {
    $this->paybox = $payboxService;
}

public static function create(ContainerInterface $container) {
    return new static(
        $container->get('paybox_services'),
    );
}

This declaration work fine, but i see sometime this in the constructor :

public function __construct(Paybox $payboxService) {
    $this->paybox = $payboxService;
}

public static function create(ContainerInterface $container) {
    return new static(
        $container->get('paybox_services'),
    );
}

They add the Type Paybox before $payboxService.

The 2 method work.

Can someone explain me the difference ? and what is the right way for inject the service ?

4
  • The difference between __construct($payboxService) and __construct(Paybox $payboxService) is plain PHP. Drupal doesn't change PHP syntax. – kiamlaluno Aug 3 '17 at 11:52
  • yes but since it's the factory method who pass dependency to the constructor, that can't be in drupal answer ?? – Kevin Aug 3 '17 at 12:15
  • It's the same as for any PHP function, called from another function, or not. – kiamlaluno Aug 3 '17 at 13:07
  • You should always type hint constructor arguments. On top of that, you should strive to use interfaces where possible, so swapping implementations is simple. (note: the Kevin above is not me). This is not a "Drupal" thing. Check the chapter on Dependency Injection in Symfony docs for a better picture. – Kevin Aug 3 '17 at 13:19
9

Both code snippets work indeed, the second one uses type declaration:

http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration

You can use type declaration to force specific arguments in your methods parameters. If, for instance, someone should create a new class from your first code snippet and inject something other that your Paybox class your class will not throw errors. In the second example you are enforcing the first parameter to be of type Paybox. If something else is passed PHP will throw errors. If you make your code available as an API for other people they can see what kind of parameters are required without checking the full logic of your encapsulated code.

Furthermore, your IDE will play nice with type hinted parameters providing you with suggestions and better doc block generation.

Not the answer you're looking for? Browse other questions tagged or ask your own question.