【问题标题】:Symfony2 getLocal() in post load lifecycle event加载后生命周期事件中的 Symfony2 getLocal()
【发布时间】:2016-04-12 06:10:54
【问题描述】:

我正在用 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 种语言。感谢您的帮助

【问题讨论】:

    标签: php symfony doctrine-orm


    【解决方案1】:

    是的,你可以。您可以将@request_stack service 注入您的侦听器,从中获取请求并读取语言环境。

    但是,有一个 Doctrine 扩展可能可以满足您的需求:Translatable

    【讨论】:

      【解决方案2】:

      感谢@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 $requestStackk
       */
      public function __construct(RequestStack $requestStackk) {
      
      
          $this->requestStack = $requestStackk;
      }
      
      
      /**
       * @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 }
      
              arguments: [@request_stack]
      

      希望这对其他人也有帮助

      【讨论】:

        猜你喜欢
        • 2012-03-30
        • 2017-01-18
        • 2011-08-21
        • 2014-06-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多