2012-10-28 48 views

回答

1

下面是重定向到一個頁面,在用戶配置中設置的語言監聽器。適應您的需求。

<?php 
namespace MyVendor\Listener; 

use Symfony\Component\HttpKernel\HttpKernelInterface; 
use Symfony\Component\HttpKernel\Event\GetResponseEvent; 
use Symfony\Component\HttpFoundation\RedirectResponse; 
use Symfony\Component\Security\Core\SecurityContextInterface; 
use Symfony\Component\Routing\RouterInterface; 
use JMS\DiExtraBundle\Annotation\Service; 
use JMS\DiExtraBundle\Annotation\InjectParams; 
use JMS\DiExtraBundle\Annotation\Observe; 

/** 
* @Service 
*/ 
class LanguageListener 
{ 
    /** 
    * @var \Symfony\Component\Security\Core\SecurityContextInterface 
    */ 
    private $securityContext; 

    /** 
    * @var \Symfony\Component\Routing\RouterInterface 
    */ 
    private $router; 

    /** 
    * @InjectParams 
    * 
    * @param \Symfony\Component\Security\Core\SecurityContextInterface $securityContext 
    * @param \Symfony\Component\Routing\RouterInterface $router 
    */ 
    public function __construct(
     SecurityContextInterface $securityContext, 
     RouterInterface $router 
    ) { 
     $this->securityContext = $securityContext; 
     $this->router   = $router; 
    } 

    /** 
    * @Observe("kernel.request") 
    * 
    * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event 
    */ 
    public function forceLanguage(GetResponseEvent $event) 
    { 
     if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) { 
      return; 
     } 

     $token = $this->securityContext->getToken(); 

     if (!$token) { 
      return; 
     } 

     if (!$this->securityContext->isGranted('ROLE_USER')) { 
      return; 
     } 

     /** @var $request \Symfony\Component\HttpFoundation\Request */ 
     $request = $event->getRequest(); 
     $locale = $request->getLocale(); 
     $route = $request->get('_route'); 

     if ('_' === $route[0]) { 
      return; 
     } 

     /** @var $user \MyVendor\Model\User */ 
     $user = $token->getUser(); 

     if ($user->getConfig()->getLanguage() !== $locale) { 
      $parameters = array_merge($request->attributes->get('_route_params'), [ 
       '_locale' => $user->getConfig()->getLanguage(), 
      ]); 

      $path = $this->router->generate($route, $parameters); 
      $event->setResponse(new RedirectResponse($path)); 
     } 
    } 
} 
3

您可以定義事件監聽器

請閱讀文檔中關於event listeners創作。

0

我相信這取決於你想要做什麼。對於大多數時候symfony及其捆綁包處理幾乎所有的語言。這意味着如果您想自定義路由,則必須使用routing.loader標記來擴展路由組件。 但是,如果您可以使用event listeners,但我不確定可以從那裏更改多少項。

0

使用上面建議的事件或者如果您需要快速的東西。

您可以覆蓋setContainer方法。

namespace My\Namespace; 

use Symfony\Bundle\FrameworkBundle\Controller\Controller; 
use Symfony\Component\DependencyInjection\ContainerInterface; 

class MyController extends Controller 
{ 
    private $foo; 

    public function setContainer(ContainerInterface $container = null) 
    { 
     parent::setContainer($container); 
     $this->foo = 'bar'; 
    } 
    // your actions 
} 
相關問題