加载后生命周期事件中的Symfony2 getLocal()


Symfony2 getLocal() in post load lifecycle event

我正在用symfony2开发一个应用程序。我面临着本地化的问题。我想在条令生命周期中的postLoad事件中设置,但可以找到一种方法。我正在使用路由方法来设置我的本地,例如:

http://example.com/en/content

这是我的听众:

namespace MyApiBundle'Listener;
use Symfony'Component'HttpFoundation'Request;
use Symfony'Component'HttpKernel'Event'GetResponseEvent;
use Symfony'Component'HttpKernel'KernelEvents;
use Symfony'Component'EventDispatcher'EventSubscriberInterface;
use Doctrine'ORM'Event'LifecycleEventArgs;

class LocaleListener
{
private $local;
public function __construct($local) {
    $this->local = $local;
}

public function postLoad(LifecycleEventArgs $args)
{

    $local= 'en'; // I need to get the local from here
    $entity = $args->getEntity();
    if(method_exists($entity, 'setLocale')) {
        $entity->setLocale($local);
    }
}

}

从这里有什么快速到达当地的方法吗?不能使用新的Request(),因为它总是返回en。我还有3种其他语言。感谢的帮助

可以。您可以将@request_stack服务注入到侦听器中,从中获取请求并读取区域设置。

然而,有一个Doctrine扩展可能会满足您的需求:可翻译

感谢@Igor Pantovic

这是我的工作,这是我当地的列表:

#/src/MyApiBUndle/Listner/LocalListner.php
namespace MyApiBundle'Listener;
use Symfony'Component'HttpFoundation'RequestStack;
use Doctrine'ORM'Event'LifecycleEventArgs;

class LocaleListener {
   
   private $requestStack;
/**
 * @param RequestStack $requestStack
 */
public function __construct(RequestStack $requestStack) {
    
    $this->requestStack = $requestStack;
}

/**
 * @param LifecycleEventArgs $args
 */
public function postLoad(LifecycleEventArgs $args)
{
    $local= $this->requestStack->getCurrentRequest()->getLocale();
    $entity = $args->getEntity();
    if(method_exists($entity, 'setLocale')) {
        $entity->setLocale($local);
    }
}

}

和我的服务

services:
my_api.listener.locale_listener:
        class:  MyApiBundle'Listener'LocaleListener
        tags:
            - { name: doctrine.event_listener, event: postLoad }
        # @request_stack must be quoted "":
        arguments: ["@request_stack"]

希望这也能帮助其他