Search code examples
phpdependenciescode-injectionsymfony4

Symfony 4 Dependency Injection


I've got class like this,

use Doctrine\ORM\EntityManagerInterface;

class LoginTools {

private $em;

public function __construct(EntityManagerInterface $em)
{
    $this->em = $em;
}

and in Controller

$logTool = new LoginTools();

Question

Does autowire should pass EntityManagerInterface to LoginTools automatically? Because when I call LoginTools class without passing the argument I get error

Too few arguments to function App\Utils\LoginTools::__construct(), 0 passed exactly 1 expected

With Regards,

Wiktor.


Solution

  • As you said, LoginTools is a service. That means, that you mustn't create it in code, like you do, Symfony creates it for you and you have just to inject this service in controller instead of EntityManagerInterface.

    The thing is that Symfony has DI container, it's purpose is creating services based on your configuration from config/services.yaml and then injecting them into other services' constructors/functions/properties. There's no magic, all this code, which creates your services and inject them into other services, is generated automatically and is saved into var/cache dir by Symfony, you can check it by yourself.