I have a lot of controllers that will need to use the Symfony TranslatorInterface for my alerts, flash messages etc.
What is the best practice to inject a service in a lot of controllers without code repetition?
My first thought was to create BaseController that will extend AbstractController, inject service there in the constructor and extend my current controller by the new BaseController.
Controllers/BaseController.php
class BaseController extends AbstractController
{
private TranslatorInterface $translator;
public function __construct(TranslatorInterface $translator)
{
$this->translator = $translator;
}
public function trans(string $id, array $parameters = [], string $domain = null, string $locale = null): string
{
return $this->translator->trans($id, $parameters, $domain, $locale);
}
}
And from here in the controller that i will need a lot of translations i could:
Controllers/FooController.php
class RegisterController extends BaseController //instead of AbstractController
{
public function foo(): Response
{
$this->trans('test.message');
}
...
}
Is this a good practice or should i traditionally inject TranslatorInterface inside parameters of my functions? Or maybe every translated controller should have constructor with it?