Detect locale and alter url (redirect) to include

2019-02-19 02:20发布

What i want to do is, to detect the language of a users browser and redirect him to a page containing the locale in url.

I thought, the easiest way would be, to register a kernel listener. So that is what i did:

services:
    kernel__request_listener:
        class: Me\MainBundle\Listener\KernelRequestListener
        tags:
            - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
        calls:
            - [ setContainer, [ @service_container ] ]

KernelRequestListener.php

...
/**
 * @Service
 */
class KernelRequestListener
{
    /**
     * @Observe("kernel.request")
     */
    public function onKernelRequest( GetResponseEvent $response )
    {

    if( $newLocale = $this->newLocale() )
    {
        $parmArray = $request->get('_route_params');
        $parmArray['_locale'] = $newLocale;

        $redirectResponse = new RedirectResponse( $this->getContainer()->get('router')->generate($request->get('_route'), $parmArray) );
        $redirectResponse->headers->setCookie( new Cookie('b_locale', $newLocale, time() + 2592000) );

        $response->setResponse( $redirectResponse );
    }
    }
...
}

The method $this->newLocale() just detects if the user should be redirected to another language and returns the new language code (i.e. DE or FR).

Here comes the problem: I am using assetics to compress the js files and jms/i18n-routing-bundle to do the locale-based routing. When the kernel listener switches locale, the page starts loading the js files over and over again. also, there are several pages (i.e. the profiler, login/logout etc.) where no redirect should take place as it makes no sense or breaks smthing.

Is a kernel listener the right place to do such a redirection or is there any better place. How to resolve the problems above?

1条回答
再贱就再见
2楼-- · 2019-02-19 02:45

Add, before your code:

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

    $request = $event->getRequest();
    if ($request->getRequestFormat() !== 'html') {
        return;
    }

    [CODE]
查看更多
登录 后发表回答