绝对,我已经做到了!
1)首先创建你的听众:
<?php
namespace Sybio\Bundle\WebsiteBundle\Services\Listener;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\Routing\Router;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\HttpKernel;
/**
* User listener : redirect user depending on his informations
*/
class UserListener
{
/**
* @var Container
*/
private $container;
/**
* @var Router
*/
private $router;
/**
* Constructor
*
* @param Container $container
* @param Router $router
*/
public function __construct(Container $container, Router $router)
{
$this->container = $container;
$this->router = $router;
}
public function onKernelRequest(GetResponseEvent $event)
{
if ($this->container->get('security.context')->getToken()
&& $this->container->get('security.context')->isGranted('ROLE_PENDING')
&& $event->getRequest()->attributes->get('_controller') != 'Sybio\Bundle\WebsiteBundle\Controller\UserController::completeInformationAction'
&& $event->getRequest()->attributes->get('_controller') != 'Sybio\Bundle\WebsiteBundle\Controller\SecurityController::logoutAction'
&& HttpKernel::MASTER_REQUEST == $event->getRequestType()
) {
$event->setResponse(new RedirectResponse($this->router->generate('sybiowebsite_user_complete_information')));
}
}
}
笔记 :
- 检查用户是否已登录,然后有 ROLE_PENDING (这意味着不完整的配置文件)
- 测试用户是否已经在他可以完成其个人资料的操作中,否则你将有一个无限的重定向循环!
- 允许用户注销(当然是可选的)
- 检查您是否在主请求中,否则它也将应用于 ESI、渲染操作(树枝中的渲染控制器)等......它会崩溃!
如果所有条件都为真,则侦听器重定向到完整的个人资料页面!
2)注册你的听众:
# services.yml or config.yml
sybio.user_listener:
class: Sybio\Bundle\WebsiteBundle\Services\Listener\UserListener
arguments:
- @service_container
- @router
tags:
- { name: kernel.event_listener, event: kernel.request, method: onKernelRequest}
3)最后一步是定义用户配置文件何时不完整,并为其赋予 ROLE_PENDING:
// Entity -> User.php :
/**
* Get Roles (security)
*
* @return array
*/
public function getRoles()
{
$roles = array();
// Manage your roles ...
if (!$this->email) { // or what you want
$roles[] = 'ROLE_PENDING';
}
return $roles;
}
而已 !