Skip to content
Advertisement

When to use action injection and when to inject dependencies on the constructor for controllers?

In Symfony you can direct inject a service into a controller function:

use AppServiceFooService;

class FooController
{
    public function one(FooService $fooService){
        $fooService->doSomething();
    }
}

I’m looking for reasons/guides when to inject and when not to inject. What is the performance price for either one, or pro/cons, e.g.:

  • Must you always aim to not have a __construct()?
  • If all methods in a class use FooService, do I still load them in each method, or do I now use the __construct?

How do I decide which solution I implement?

My current logic is “as much as you can use action injection, as this saves time initializing all the Controllers, with the downside that the method calls are a tad slower because it now has to be done there”

I think this topic is on the edge of what is allowed on SO, I’m looking for a guiding ruleset, not a review or opinion.

Advertisement

Answer

There is not a significant performance or memory advantage in either case, the injected services are references, not new instances.

Most modern designs would not have controllers with many different methods in any case. And if many public methods of the same class had very different dependencies, maybe all these methods did not belong in the same class to begin with?

In the end, these design differences are an stylistic choice. Nowadays, constructor injection tends to be preferred (around me, at least), because since the dependencies are what the class needs to have to be in a valid stated to work, passing them at instantiation time seems more logical to many.

There is nothing inherently wrong in passing this as method parameters in many cases (as in having any other type of callables as a parameter), but what I believe is best is to think of controller actions as any other method:

  • how does the method reads more clearly?
  • would a method consumer need to know the class dependencies, and change the dependencies at call-time, or is that beyond the responsibilities of the consumer?
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement