Symfony2:在切换区域设置期间向后Uri(推荐人)

时间:2011-09-14 09:42:11

标签: php localization symfony referrer

我想实现区域设置切换器,但似乎没有运气......

以下代码不起作用,因为(推荐人)包含旧版本的区域设置...

如何使用新的locale值重定向到旧的Referrer URI?

- routing.yml

hello:
  pattern:  /{_locale}/hello/{name}
  defaults: { _controller: JetInformBundle:Default:index, name: 'alexander' }
  requirements:
    _locale: ^en|de|ru|uk$

about:
  pattern:  /{_locale}/about
  defaults: { _controller: JetInformBundle:Default:about }
  requirements:
    _locale: ^en|de|ru|uk$

locale:
  pattern:  /locale/{locale}
  defaults: { _controller: JetInformBundle:Locale:index }

- DefaultController.php

<?php

namespace Jet\InformBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;

class DefaultController extends Controller
{
    public function indexAction($name, Request $request)
    {
        $request->getSession()->set('referrer', $request->getRequestUri());
        return $this->render('JetInformBundle:Default:index.html.twig',
                             array('name' => $name));
    }

    public function aboutAction(Request $request)
    {
        $request->getSession()->set('referrer', $request->getRequestUri());
        return $this->render('JetInformBundle:Default:about.html.twig'));
    }
}

- LocaleController.php

<?php

namespace Jet\InformBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;

class LocaleController extends Controller
{
    public function indexAction($locale, Request $request)
    {
        $session = $request->getSession();

        if ($request->hasSession())
            $session->setLocale($locale);

        return $this->redirect($session->get('referrer'));
    }
}

- index.html.twig

{% extends '::base.html.twig' %}

{% block body %}
<h1>{% trans %}hello.name{% endtrans %} {{ name }}!</h1>
<h3>{% trans %}your.locale{% endtrans %} [{{ app.request.get('_locale') }}]</h3>

{% include 'JetInformBundle:Default:locales.html.twig' %}

<div>
    <p>{% trans%}return.to{% endtrans%} <a href="{{ path('about', { '_locale':   app.request.get('_locale') }) }}">About</a></p>
</div>
{% endblock %}

-- locales.html.twig

<div class="langs">
    <ul>
        <li>
            {% if app.request.get('_locale') == 'ru' %}
                Русский
            {% else %}
                <a href="{{ path('locale', { 'locale': 'ru' }) }}">Русский</a>
            {% endif %}
        </li>
        <li>
            {% if app.request.get('_locale') == 'en' %}
                English
            {% else %}
                <a href="{{ path('locale', { 'locale': 'en' }) }}">English</a>
            {% endif %}
        </li>
        <li>
            {% if app.request.get('_locale') == 'uk' %}
                Украiнська
            {% else %}
                <a href="{{ path('locale', { 'locale': 'uk' }) }}">Украiнська</a>
            {% endif %}
        </li>
        <li>
            {% if app.request.get('_locale') == 'de' %}
                Deutsch
            {% else %}
                <a href="{{ path('locale', { 'locale': 'de' }) }}">Deutsch</a>
            {% endif %}
        </li>
    </ul>
</div>

4 个答案:

答案 0 :(得分:10)

让我告诉你我的解决方案。我编写了内核事件监听器:

<service id="expedio.simple.listener" class="Expedio\SimpleBundle\Listener\Kernel">
      <tag name="kernel.event_listener" event="kernel.request" method="onKernelRequest" />
      <argument type="service" id="router" />
  </service>

如下:

namespace Expedio\SimpleBundle\Listener;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;

class Kernel {

    /**
     * @var \Symfony\Component\DependencyInjection\ContainerInterface
     */
    private $router;

    public function __construct(\Symfony\Component\Routing\Router $router) {
        $this->router = $router;
    }

    public function onKernelRequest(GetResponseEvent $event) {
        if ($event->getRequestType() !== \Symfony\Component\HttpKernel\HttpKernel::MASTER_REQUEST) {
            return;
        }

        /** @var \Symfony\Component\HttpFoundation\Request $request  */
        $request = $event->getRequest();
        /** @var \Symfony\Component\HttpFoundation\Session $session  */
        $session = $request->getSession();

        $routeParams = $this->router->match($request->getPathInfo());
        $routeName = $routeParams['_route'];
        if ($routeName[0] == '_') {
            return;
        }
        unset($routeParams['_route']);
        $routeData = array('name' => $routeName, 'params' => $routeParams);

        //Skipping duplicates
        $thisRoute = $session->get('this_route', array());
        if ($thisRoute == $routeData) {
            return;
        }
        $session->set('last_route', $thisRoute);
        $session->set('this_route', $routeData);
    }
}

每次用户打开页面时,它只保存最后的请求路由数据。在控制器中,当用户想要更改语言环境时,我会这样做:

/**
 * @Route("/setlocale/{locale}", name="set_locale")
 * @param string $locale
 * @return array
 */
public function setLocaleAction($locale) {
    /** @var \Symfony\Component\HttpFoundation\Session $session  */
    $session = $this->get('session');
    $session->setLocale($locale);
    $last_route = $session->get('last_route', array('name' => 'index'));
    $last_route['params']['_locale'] = $locale;
    return ($this->redirect($this->generateUrl($last_route['name'], $last_route['params'])));
}

答案 1 :(得分:3)

我使用

方法提供我的解决方案
$request->headers->get('referer');

按照gilden的建议

/**
 * Your locale changing controller
 */
public function localeAction($locale)
{
    $request = $this->get('request');
    $router = $this->get('router');
    $context = $router->getContext();
    $frontControllerName = basename($_SERVER['SCRIPT_FILENAME']);

    if($request->hasSession())
    {
        $session = $request->getSession();
        $session->setLocale($locale);
        $context->setParameter('_locale', $locale);

        //reconstructs a routing path and gets a routing array called $route_params
        $url = $request->headers->get('referer');
        $urlElements = parse_url($url);
        $routePath = str_replace('/' . $frontControllerName, '', $urlElements['path']); //eliminates the front controller name from the url path
        $route_params = $router->match($routePath);

        // Get the route name
        $route = $route_params['_route'];

        // Some parameters are not required to be used, filter them
        // by using an array of ignored elements.
        $ignore_params = array('_route' => true, '_controller' => true, '_locale' => true);
        $route_params = array_diff_key($route_params, $ignore_params);

        $url = $this->get('router')->generate($route, $route_params);

        return $this->redirect($url);
    }
}

答案 2 :(得分:1)

您必须在会话中存储路线属性的数组,而不是单个网址。

/**
 * You should set the 'referrer' in every controller in your application. This
 * should probably be handled as an event to save all the hassle.
 */
public function anyAction(Request $request)
{
    $request->getSession()->set('referrer', $request->attributes->all());

    // ...
}

/**
 * Your locale changing controller
 */
public function localeAction($locale, Request $request)
{
    if($request->hasSession())
    {
        $session = $request->getSession();
        $session->setLocale($locale);

        $route_params = $session->get('referrer');

        // Get the route name
        $route = $route_params['_route'];

        // Some parameters are not required to be used, filter them
        // by using an array of ignored elements.
        $ignore_params = array('_route' => true, '_controller' => true);
        $route_params = array_diff_key($route_params, $ignore_params);

        $url = $this->get('router')->generate($route, $route_params);
        return $this->redirect($url);
    }
}

供将来参考以及任何对此有绊脚石的人:您不必通过在每个控制器中设置referrer属性来存储会话中的headers属性。您可以从$request->headers->get('referer'); // Single 'r' everywhere! 属性中检索上一个网址:

Request

有关其他信息,请参阅:

  • github
  • 上的Symfony2 ParameterBag课程
  • github
  • 上的Symfony2 {{1}}课程

答案 3 :(得分:0)

吉尔登,非常感谢你的想法,但无论如何都不行......

这是控制器LOCALE SWITCHER:

class LocaleController extends Controller
{
public function changeAction($locale, Request $request)
{
    if ($request->hasSession())
    {
        $session = $request->getSession();
        $session->setLocale($locale);

        $route_params = $session->get('jet_referrer');
        $route_name = $route_params['_route'];

        // Some parameters are not required to be used, filter them
        // by using an array of ignored elements.
        $ignore_params = array('_route' => true, '_controller' => true,
                               '_template_default_vars' => true);
        $route_params = array_diff_key($route_params, $ignore_params);

        $url = $this->get('router')->generate($route_name, $route_params);
        return $this->redirect($url);
    }
}
}

以下是BUSINESS LOGIC的控制器:

/**
 * @Route("/{_locale}")
 */
class TestController extends Controller
{
/**
 * @Route("/", name="_test")
 * @Template()
 */
public function indexAction(Request $request)
{
    $request->getSession()->set('jet_referrer', $request->attributes->all());
    return array();
}

/**
 * @Route("/hello/{name}", name="_test_hello")
 * @Template()
 */
public function helloAction($name, Request $request)
{
    $request->getSession()->set('jet_referrer', $request->attributes->all());
    return array('name' => $name);
}
}

关于array_key_diff()的IGNORED参数......

_controller
_locale
_route
_template
_template_default_vars
_template_vars

我试图将其中的一些包含在新一代路线中,但没有运气...... 不明白发生了什么......

这似乎只是一个黑客......我们是否有更多的软化方式来实现Symfony2中的这个简单功能? RAW PHP允许我做那么多&amp;更容易......

再次感谢。