Serghei
Serghei

Reputation: 41

Symfony 4 autowiring in Entity not working

I`m trying to autowire in my User Entity Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface and receiving error Too few arguments to function App\Entity\User::__construct().

public function __construct(UserPasswordEncoderInterface $encoder)
{
    $this->packages = new ArrayCollection();
    $this->passwordEncoder = $encoder;
}

In my services.yaml

services:
# default configuration for services in *this* file
_defaults:
    autowire: true      # Automatically injects dependencies in your services.
    autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
    public: false       # Allows optimizing the container by removing unused services; this also means
                        # fetching services directly from the container via $container->get() won't work.
                        # The best practice is to be explicit about your dependencies anyway.

# makes classes in src/ available to be used as services
# this creates a service per class whose id is the fully-qualified class name
App\:
    resource: '../src/*'
    exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'

# controllers are imported separately to make sure services can be injected
# as action arguments even if you don't extend any base controller class
App\Controller\:
    resource: '../src/Controller'
    tags: ['controller.service_arguments']

Upvotes: 3

Views: 5126

Answers (1)

Magnesium
Magnesium

Reputation: 617

As stated in the comment, Entities are specifically not treated as services, therefore cannot use autowiring.

Entities are supposed to be used for simple data manipulations. If you need to access other Symfony components, one of your options is to create a manager class that handles the additional work or rely on event listeners.

Upvotes: 5

Related Questions