Symfony 6 parent controller to child controller dependency injection
P粉208469050
2023-08-17 20:19:03
<p>I have a base controller class that contains some utility methods that all child controllers use. Currently it has 3 dependencies, but there may be more in the future. So whenever I want to add a dependency to a child controller, I now have an issue where I think there are too many directives for dependency injection. </p>
<pre class="brush:php;toolbar:false;">abstract class BaseController extends AbstractController
{
public function __construct(
protected readonly SerializerInterface $serializer,
protected readonly ValidatorInterface $validator,
private readonly ResponseGenerator $responseGenerator,
) {
}
...
}
class ChildController extends BaseController
{
// All parent class injections are required in all child classes.
public function __construct(
SerializerInterface $serializer,
ValidatorInterface $validator,
ResponseGenerator $responseGenerator,
private readonly SomeRepository $someRepository,
...insert any other child controller-specific dependencies here.
) {
parent::__construct($serializer, $validator, $responseGenerator);
}
...
}</pre>
<p>I tried using <code>$this->container->get('serializer')</code> in the base controller, but that didn't work because <code>AbstractController: :$container</code> is defined through injection, but has no constructor, so <code>parent::__construct()</code> cannot be called. Also, it doesn't give me a <code>validator</code>, so even if it works, it only solves part of the problem. </p>
<p>I tried looking for properties that I could use, like </p>
<pre class="brush:php;toolbar:false;">abstract class BaseController extends AbstractController
{
#[Inject]
protected readonly SerializerInterface $serializer;
#[Inject]
protected readonly ValidatorInterface $validator;</pre>
<p>But nothing similar was found (PHP-DI has it, but Symfony doesn't). </p>
<p>Is there a way to somehow eliminate duplicate dependencies in child controllers? </p>
What you need is to be called a Service Subscriber
In Symfony, when controllers inherit
AbstractController
, they are service subscribers, which means they are injected with a library containing some common services (such as twig, serializers, form builders, etc. ) small container.If you want some "common" services that your child controllers will use, you can extend the list by overriding
getSubscribedServices()
in the parent controller. Or if your controller does not inherit the default controller provided by Symfony, you just need to implement your own controller:If your controller is a service (which I guess it already is), Symfony will use setter injection to inject the container into your controller.
The code will look like this: