Felix
Felix

Reputation: 33

Symfony Dependency injection to class

I have a class in App\Util which needs the MailerInterface Dependency. So I added it directly to the constructor like this:

public function __construct(MailerInterface $mailer)
    {
        $this->mailer = $mailer;
    }

Then I added the argument in the services.yaml:

services: 
        ...
        App\Util\OwnerMailValidation:
              arguments: ['@mailer']

In the end I used exactly the same code as provided by the symfony documentation but I keep getting the error: Too few arguments to function App\Util\OwnerMailValidation::__construct(), 0 passed [...] 1 expected

My complete servicey.yaml:

services:
    _defaults:
        autowire: true      
        autoconfigure: true

    App\:
        resource: '../src/'
        exclude:
            - '../src/DependencyInjection/'
            - '../src/Entity/'
            - '../src/Kernel.php'
            - '../src/Tests/'

    App\Controller\:
        resource: '../src/Controller/'
        tags: ['controller.service_arguments']

    App\Util\OwnerMailValidation:
        class: App\Util\OwnerMailValidation
        arguments: ['@mailer']

Upvotes: 0

Views: 1375

Answers (2)

R4ncid
R4ncid

Reputation: 7139

If you have a single implementation of MailerInterface you shouldn't write anything in your service.yaml
Symfony can figure it out on his own.
If it still doesn't work try to do this

App\Util\OwnerMailValidation:
    arguments:
      $mailer: '@<the class that implements MailerInteface that you want to inject>'
      

As @cerad said autowiring works if you inject your class into another.
If you're doing $validation = new OwnerMailValidation(); it just won't work because it requires a MailerInterface in the constructor.
You should inject your OwnerMailValidation into the controller method or into the class constructor.

Upvotes: 1

nikserg
nikserg

Reputation: 382

Try this config:

services: 
        ...
        App\Util\OwnerMailValidation:
           class: App\Util\OwnerMailValidation

Upvotes: 0

Related Questions