phptools-docs icon indicating copy to clipboard operation
phptools-docs copied to clipboard

Simplify usage of constructor based dependency injection (DI)

Open Zerotask opened this issue 3 years ago • 0 comments

When working with a framework like Symfony which uses constructor based dependency injection (prior PHP 8.0) you have to add 3x basically the same:

<?php

class User
{
    private SystemConfigService $systemConfigService;

    public function __construct(SystemConfigService $systemConfigService)
    {
        $this->systemConfigService = $systemConfigService;
    }
}

Therefore it would be great to have a quick fix to write just 1x SystemConfigService $systemConfigService. For example you add this as a parameter to your constructor, then you could quick fix it and create:

  • $this->systemConfigService = $systemConfigService;
  • private SystemConfigService $systemConfigService;

Note: since PHP 8.0 you can write it as simple as:

<?php

class User
{
    public function __construct(private SystemConfigService $systemConfigService)
    {
    }
}

So the quick fix should consider if there is a visibility before the parameter's data type.

Zerotask avatar Nov 04 '22 17:11 Zerotask