setLocale不能处理symfony2应用程序

时间:2016-05-14 09:50:41

标签: symfony

我按照此tutorial说明将区域设置更改为“粘性”。

并创建了一个用户请求更改语言环境的操作。

LocaleListener

<?php
namespace AppBundle\EventListener;

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

class LocaleListener implements EventSubscriberInterface
{
    private $defaultLocale;

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

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

        // try to see if the locale has been set as a _locale routing parameter
        if ($locale = $request->attributes->get('_locale')) {
            $request->getSession()->set('_locale', $locale);
        } else {
            // if no explicit locale has been set on this request, use one from the session
            $request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
        }
    }

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

目录结构:

enter image description here

服务

services:
     app.locale_listener:
            class: AppBundle\EventListener\LocaleListener
            arguments: ['%kernel.default_locale%']
            tags:
                - { name: kernel.event_subscriber }

行动

/**
     * @Route("/change-locale/{locale}", name="change_locale", defaults={"locale" = "it"})
     */
    public function changeLocaleAction(Request $request) {

        $request->setLocale('it');

        $ref = $request->headers->get('referer');
        return $this->redirect($ref);
    }

但它不起作用,我没有收到任何错误。为什么会出现这个问题?

1 个答案:

答案 0 :(得分:1)

您在请求侦听器中请求_locale属性,但在路由定义中,正在设置的属性为locale(请注意缺少前导下划线)。

您需要相应地更新路线定义:

/**
 * @Route("/change-locale/{_locale}", name="change_locale", defaults={"_locale" = "it"})
 */
public function changeLocaleAction(Request $request)
{
    // ...
}