我试图弄清楚为什么我的一个控制器中的语言环境不同以及何时从请求堆栈中获取请求。
以下是我的一条路线的示例:“ website.com/nl”
/**
* Main page of the website
* @Route("/{_locale}",
* name="home",
* defaults={"_locale": "nl"},
* requirements={
* "_locale": "nl|en|fr"
* },
* )
* @param Request $request
* @param $_locale
* @return \Symfony\Component\HttpFoundation\Response
*/
public function home(
Request $request,
$_locale
) {
// $_locale === "nl"
// $request->getLocale() === "nl"
}
根据网址的预期,区域设置为NL
现在,当我需要在服务或事件侦听器之一中使用区域设置时,我需要使用RequestStack->getCurrentRequest()->getLocale()
。但是,此语言环境始终设置为语言环境:“ en”
服务映射:
app.doctrine.locale_listener:
class: App\EventListener\LocaleListener
public: false
arguments: ["@request_stack"]
lazy: true
tags:
- { name: "doctrine.orm.entity_listener", entity: App\Entity\Translation\Translatable, event: postLoad }
实体侦听器:
namespace App\EventListener;
use App\Entity\Translation\Translatable;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\HttpFoundation\RequestStack;
class LocaleListener
{
private $currentLocale;
public function __construct(RequestStack $rs)
{
$this->currentLocale = $rs->getCurrentRequest()->getLocale();
// $this->currentLocale === "en"
}
public function postLoad(Translatable $translatable, LifecycleEventArgs $args)
{
$translatable->setLocale($this->currentLocale);
// e.g. url: mywebsite.be/nl
// Why is $this->currentLocale === "en"?
}
}
我在做什么错了?