2
votes

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']
1
You see that "exclude: ...Entity..." portion of services.yaml? That specifically says to NOT autowire anything under the Entity directory. Doctrine entities are not services. For most practical purposes, you cannot inject stuff into them.Cerad

1 Answers

4
votes

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.