使用Symfony3 LocaleSubscriber管理语言环境

时间:2017-11-04 19:04:10

标签: php symfony

我在使用Symfony 3的locale参数时遇到了一些麻烦。我尝试了很多我在Stack上找到的东西,但似乎没什么用。

我已按照官方文档:https://symfony.com/doc/current/session/locale_sticky_session.html

LocaleSubscriber.php

<?php

namespace AppBundle\EventSubscriber;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

use Symfony\Component\HttpKernel\HttpKernel;

class LocaleSubscriber implements EventSubscriberInterface
{
    private $defaultLocale;

    public function __construct($defaultLocale = 'en')
    {
        $this->defaultLocale = $defaultLocale;
    }

    public function onKernelRequest(GetResponseEvent $event)
    {

        if (HttpKernel::MASTER_REQUEST != $event->getRequestType()) {
            return;
        }

        $request = $event->getRequest();
        if (!$request->hasPreviousSession()) {
            return;
        }

        // try to see if the locale has been set as a _locale routing parameter
        if ($locale = $request->get('_locale')) {
            $request->set('_locale', $locale);
        } else {
            $request->set('_locale', $this->defaultLocale);
        }
    }

    public static function getSubscribedEvents()
    {
        return array(
            // must be registered after the default Locale listener
            KernelEvents::REQUEST => array(array('onKernelRequest', 17)),
        );
    }
}

config.yml

framework:
#esi: ~
translator: { fallbacks: ['%locale%'] }

service.yml

AppBundle\EventSubscriber\LocaleSubscriber:
    arguments: ['%kernel.default_locale%']
    tags: [kernel.event_subscriber]

AdminController

namespace AdminBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class AdminController extends Controller
{
    public function homeAction(Request $request)
    {
        var_dump($request->getLocale());
        var_dump($request->get('_locale'));
        return $this->render('AdminBundle:home:home.html.twig');
    }
}

HTML链接:

<li><a href="{{-path(app.request.get('_route'), app.request.get('_route_params')|merge({'_locale' : 'fr'}))-}}">FR</a></li>
<li><a href="{{-path(app.request.get('_route'), app.request.get('_route_params')|merge({'_locale' : 'en'}))-}}">EN</a></li>

问题:当我尝试切换语言时,参数_locale已更改,但文本不会切换语言。根据我的messages.en.yml。“/ test”,“testfr”必须是“testen”

点击“FR”链接时我的var_dump: string(2)“fr”string(2)“fr”

点击“EN”链接后我的var_dump: string(2)“fr”string(2)“en” 我想这不正常..

如果有人可以帮助我,那会很好,可以消除头痛。

由于

编辑:翻译器采用“locale”参数,当我点击其中一个链接时,该参数不会改变。我还在调查。

1 个答案:

答案 0 :(得分:0)

最后,发现了问题:

   if (!$request->hasPreviousSession()) {
        return;
    } 

只需评论这部分代码,现在一切都很好。