When you build services with many dependencies, two classic problems emerge:
- The code becomes harder to maintain.
- Each request can end up initializing more dependencies than it actually needs.
Instantiating lightweight PHP objects is usually cheap. What can become expensive is initializing deep dependency trees or services that establish connections, load configurations, initialize SDKs, or perform extra work during instantiation.
Symfony offers several mechanisms to control when these dependencies are instantiated without sacrificing clean architecture.
Here are three practical techniques, available via attributes starting in Symfony 7.1, to cut down on unnecessary work in the service container.
1. Divide and conquer: dependency injection in controller actions
A common issue in controllers is accumulating too many dependencies in the constructor.
Imagine a controller that handles creating, updating, and deleting articles. Each operation requires its own services, but they all end up injected into the same constructor:
final class ArticleController extends AbstractController
{
public function __construct(
private ArticleCreateService $createService,
private ArticleUpdateService $updateService,
private ArticleDeleteService $deleteService,
) {
}
// ...
}
The problem is that the controller must resolve all those dependencies when it is instantiated, regardless of which action ends up executing. That means: even if the current request only creates an article, Symfony has already had to instantiate the update and delete services as well (along with their entire dependency trees).
A much more precise alternative is injecting dependencies directly into each action’s arguments:
final class ArticleController extends AbstractController
{
#[Route('/article', methods: ['POST'])]
public function create(ArticleCreateService $service): Response
{
// Solo se necesita el servicio de creación.
}
#[Route('/article/{id}', methods: ['PUT'])]
public function update(
int $id,
ArticleUpdateService $service
): Response {
// Solo se necesita el servicio de actualización.
}
#[Route('/article/{id}', methods: ['DELETE'])]
public function delete(
int $id,
ArticleDeleteService $service
): Response {
// Solo se necesita el servicio de eliminación.
}
}
Symfony relies on its argument resolution mechanism to identify the services required by each action and inject them only when needed.
This means that ArticleDeleteService, for example, does not need to be resolved when executing the create() action.
Why does this work well?
- It reduces the dependencies required by each controller.
- It avoids resolving services exclusive to other operations.
- It simplifies unit testing (you can test each action in isolation without dragging along unnecessary dependencies).
- It promotes separation of concerns.
Additionally, it keeps controllers lean without having to resort to manual service containers or hand-rolled service locators tailored just for the controller.
2. #[Lazy]: defer heavy dependency initialization
There are scenarios where a service needs to be aware of a dependency, but won’t necessarily use it in every operation.
Picture a service responsible for creating articles that also supports uploading images. Not every article will have an associated image.
A traditional implementation would look like this:
final class ArticleCreateService
{
public function __construct(
private readonly ImageUploadService $imageUploader,
) {
}
public function create(ArticleData $data): Article
{
$article = new Article(
$data->title,
$data->content
);
if ($data->image !== null) {
$article->setImagePath(
$this->imageUploader->upload($data->image)
);
}
return $article;
}
}
Even when the image upload service is never used, Symfony still has to resolve it to construct ArticleCreateService. As a result, every article creation without an image still initializes ImageUploadService and its full dependency tree (potentially database connections, remote storage clients, etc.).
We can alter this behavior by using the #[Lazy] attribute:
use Symfony\Component\DependencyInjection\Attribute\Lazy;
final class ArticleCreateService
{
public function __construct(
#[Lazy]
private readonly ImageUploadService $imageUploader,
) {
}
public function create(ArticleData $data): Article
{
$article = new Article(
$data->title,
$data->content
);
if ($data->image !== null) {
$article->setImagePath(
$this->imageUploader->upload($data->image)
);
}
return $article;
}
}
What changes?
Instead of directly injecting the real service, Symfony provides a proxy object that represents that dependency.
The real service and its dependency tree are initialized only when the proxy is first interacted with (that is, when a method on $this->imageUploader is called).
In our example, if the article does not include an image, upload() is never invoked, and the initialization of ImageUploadService is completely skipped.
When should you use #[Lazy]?
- When a dependency has a non-trivial initialization cost.
- When its execution depends on conditions that are not always met.
- When the service pulls in transitive dependencies that are also expensive to initialize.
Keep a few key considerations in mind:
- Not every dependency needs to be lazy. Creating and maintaining a proxy also introduces overhead. It rarely pays off for small, cheap services.
- Keep proxy compatibility in mind. Prior to PHP 8.4,
finalandreadonlyclasses require extra care. In those situations, you can rely on interfaces to generate compatible proxies. - Keep constructors clean. Deferring construction should never be an excuse to slip network calls, I/O operations, or business logic into constructors. A proxy only postpones instantiation; it doesn’t change sound design principles.
A note on versions: Symfony 6.2 introduced native support for lazy services, and Symfony 6.3 allowed configuring them via #[Autowire(lazy: true)]. The #[Lazy] attribute used in this example is available starting in Symfony 7.1.
3. #[AutowireLocator]: select strategies without instantiating all implementations
Imagine you need to process different data formats: XML, Markdown, and a custom format.
A straightforward approach would be injecting all parsers into the constructor:
final class DataProcessor
{
public function __construct(
private XmlParserService $xmlParser,
private DbParserService $dbParser,
private MdParserService $mdParser,
) {
}
// ...
}
However, this introduces a direct dependency on every single implementation and forces the container to resolve all of them, even when you only need one to handle the request.
A cleaner alternative is using a common interface paired with a ServiceLocator.
First, define the contract:
interface ParserInterface
{
public function toArray(string $payload): array;
}
Next, register the implementations in a locator using #[AutowireLocator]:
use Psr\Container\ContainerInterface;
use Symfony\Component\DependencyInjection\Attribute\AutowireLocator;
final class DataProcessor
{
public function __construct(
#[AutowireLocator([
'xml' => XmlParserService::class,
'db' => DbParserService::class,
'md' => MdParserService::class,
])]
private readonly ContainerInterface $parsers,
) {
}
public function handle(string $format, string $payload): array
{
if (!$this->parsers->has($format)) {
throw new \InvalidArgumentException(
sprintf('Unsupported format "%s".', $format)
);
}
/** @var ParserInterface $parser */
$parser = $this->parsers->get($format);
return $parser->toArray($payload);
}
}
Now DataProcessor depends on the contract for accessing parsers without needing direct knowledge of their concrete classes.
The locator acts as a restricted container: it holds references to available services and retrieves each one on demand by its key.
The crucial difference is that the services are not all instantiated when DataProcessor is constructed. Each implementation is resolved only when requested via get().
Why does this work well?
- It avoids initializing unused implementations.
- It reduces coupling to concrete classes.
- It allows adding new strategies without altering the processor’s core logic.
- It makes testing and mocking implementations straightforward.
Bonus tip: avoid maintaining the implementation map manually
If you have many parsers and they change frequently, you can leverage tags to discover them automatically.
For example, tag the implementations using #[AutoconfigureTag]:
use Symfony\Component\DependencyInjection\Attribute\AutoconfigureTag;
#[AutoconfigureTag('app.parser')]
interface ParserInterface
{
public function toArray(string $payload): array;
public static function getFormat(): string;
}
Each implementation provides its own key:
final class XmlParserService implements ParserInterface
{
public static function getFormat(): string
{
return 'xml';
}
public function toArray(string $payload): array
{
// ...
}
}
And the locator can be configured using defaultIndexMethod:
#[AutowireLocator(
'app.parser',
defaultIndexMethod: 'getFormat'
)]
private readonly ContainerInterface $parsers;
This way, Symfony builds the locator from the tagged services and calls the specified method to determine each implementation’s key.
Whenever you need to add a new parser, simply implement the interface and return its key—no changes required to the consumer’s configuration map.
Optimization is about precision, not quantity
These three techniques are not magic, nor are they a replacement for good architecture. They are targeted mechanisms that let you get more out of Symfony’s service container.
The general rule is simple: don’t resolve dependencies an operation doesn’t need, and don’t initialize services before they are actually used.
Each technique fits a distinct scenario:
- Action injection: when different endpoints require different services.
#[Lazy]: when a dependency might not be called during a service’s execution.#[AutowireLocator]: when you need to dynamically select an implementation among several alternatives.
Naturally, you shouldn’t apply these techniques blindly. Symfony’s dependency injection is already highly optimized thanks to its compiled container, and adding proxies or locators carries its own cost.
The best approach is to first identify where unnecessary dependencies are being resolved, analyze service runtime behavior, and apply the appropriate mechanism.
In the end, optimization isn’t about writing less code or avoiding every single object instantiation. It’s about ensuring each request performs only the work it actually requires.