我需要在Symfony2中添加必须在每个请求上调用的函数。 (请求&会话上的语言检测)添加在Symfony2中的每个请求上调用的函数
我想在我的Controller类的构造函数中执行此操作,但容器未知/创建。
对此有何建议?
我需要在Symfony2中添加必须在每个请求上调用的函数。 (请求&会话上的语言检测)添加在Symfony2中的每个请求上调用的函数
我想在我的Controller类的构造函数中执行此操作,但容器未知/创建。
对此有何建议?
下面是重定向到一个页面,在用户配置中设置的语言监听器。适应您的需求。
<?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));
}
}
}
您可以定义事件监听器
请阅读文档中关于event listeners创作。
我相信这取决于你想要做什么。对于大多数时候symfony及其捆绑包处理几乎所有的语言。这意味着如果您想自定义路由,则必须使用routing.loader
标记来扩展路由组件。 但是,如果您可以使用event listeners,但我不确定可以从那里更改多少项。
使用上面建议的事件或者如果您需要快速的东西。
您可以覆盖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
}