0

I know I can use this in a controller:

$this->get('translator')->trans('key_name')

...but how do I get reference to the translator in a Symfony2 GetResponseEvent or FilterResponseEvent event?

I know I can use ->getRequest() but I don't see how I can get it from the Request object either.

1 Answer 1

7

In services.yml you just need to add @translator service reference

services.yml

services:
    mylistener:
        class: Your\Bundle\Listener\RequestListener
        arguments: [ @translator ]
        tags:
            - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }

Your/Bundle/Listener/RequestListener.php

namespace Your\Bundle\Listener;

use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;

class RequestListener
{
    protected $translator;

    public function __construct(TranslatorInterface $translator)
    {
        $this->translator = $translator;
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        $this->translator->trans('key_name');
    }
}
1
  • This doesn't work in Symfony 3. The argument [ @translator ] is invalid YAML. [ '@translator'] passes the YAML test but isn't passed into the constructor as a valid TranslatorInterface type
    – pogeybait
    Commented Aug 9, 2016 at 9:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.