Building large services with many dependencies brings a whole range of performance problems. Initializing and loading such a service costs us memory, CPU, and request processing time. Let's look at three basic techniques for optimizing services in Symfony while keeping the code clean.
1. Divide and conquer
Symfony can inject a service directly into a controller method argument. Don't build a "god service". Split operations into separate micro-services, each with a single responsibility. Every service then calls only what it really needs. As a bonus you get a better structure, cleaner code, and easier refactoring down the road.
final class ArticleController extends AbstractController
{
#[Route('/article', methods: ['POST'])]
public function create(ArticleCreateService $service): Response
{
// ...
}
#[Route('/article/{id}', methods: ['PUT'])]
public function update(int $id, ArticleUpdateService $service): Response
{
// ...
}
#[Route('/article/{id}', methods: ['DELETE'])]
public function delete(int $id, ArticleDeleteService $service): Response
{
// ...
}
}
2. #[Lazy] — defer creating a service until you need it
Sometimes you have to keep a service in the constructor, but you only use it under certain conditions. For example ArticleCreateService, which can also process an illustrative image from a form — but only if the user attached one. Thanks to the #[Lazy] attribute, the DIC creates a proxy for the service and initializes the real service only at the moment we actually reach for it in the code.
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) {
// ImageUploadService se instancuje teprve tady
$article->setImagePath(
$this->imageUploader->upload($data->image)
);
}
return $article;
}
}
When the article has no image, ImageUploadService and its dependencies are never created.
3. Service locator
An ideal tool when, for example, we're writing a service to process data sources and need to call a parser based on the data type.
public function __construct(
#[AutowireLocator([
XmlParserService::class,
DbParserService::class,
MdParserService::class
])]
private readonly ContainerInterface $parsers
) {
}
In the handle() method we then call the right parser based on the data type.
public function handle(string $payload): array
{
$parserClassName = $this->getParserClassNameByData($payload);
$parser = $this->parsers->get($parserClassName);
return $parser->toArray($payload);
}
All three parsers are registered, but only the one we actually need gets instantiated.
All three approaches aim at the same thing — not paying for creating services you won't use in a given request anyway.
Top comments (0)