如何使用 symfony 3.4 设置语言环境
How to set the locale with symfony 3.4
如何使用 symfony 3.4 (php) 更改语言环境?
我在我的数据库中为每个用户保存了语言环境。现在 this page 他们解释说你应该创建一个事件侦听器来设置语言环境。但他们只提供了一种方法——我要在其中 class 放置这个方法,以及如何使用我的 services.yml?
连接它
如果我在服务中 - 我如何访问我的用户对象以实际获取我想要设置的语言环境?
这是一个example provided by the docs on how to create an kernel request listener。
在此侦听器中,您注入 TokenStorage 服务,然后它会为您提供当前令牌以及当前登录的附加用户。然后您从用户那里获取语言环境并将其设置为请求。
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class RequestListener
{
private $tokenStorage;
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
public function onKernelRequest(GetResponseEvent $event)
{
$user = $this->tokenStorage->getToken()->getUser();
$request = $event->getRequest();
$request->setLocale($user->getLocale());
}
}
理解为什么 Symfony 需要接口的类型提示而不是 class please read the documentation。
如何使用 symfony 3.4 (php) 更改语言环境?
我在我的数据库中为每个用户保存了语言环境。现在 this page 他们解释说你应该创建一个事件侦听器来设置语言环境。但他们只提供了一种方法——我要在其中 class 放置这个方法,以及如何使用我的 services.yml?
连接它如果我在服务中 - 我如何访问我的用户对象以实际获取我想要设置的语言环境?
这是一个example provided by the docs on how to create an kernel request listener。
在此侦听器中,您注入 TokenStorage 服务,然后它会为您提供当前令牌以及当前登录的附加用户。然后您从用户那里获取语言环境并将其设置为请求。
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class RequestListener
{
private $tokenStorage;
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
public function onKernelRequest(GetResponseEvent $event)
{
$user = $this->tokenStorage->getToken()->getUser();
$request = $event->getRequest();
$request->setLocale($user->getLocale());
}
}
理解为什么 Symfony 需要接口的类型提示而不是 class please read the documentation。