您不必修改控制器,只需创建一个事件侦听器,然后在每个请求上执行您想要执行的操作。
要获取用户,只需注入安全上下文服务并获取令牌。然后,如果请求在防火墙后面,您可以获取用户。
这是一个基于官方文档的示例(未经测试,必须修改以适合您的项目):
// src/Acme/DemoBundle/EventListener/AcmeRequestListener.php
namespace Acme\DemoBundle\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\Security\Core\SecurityContextInterface;
class AcmeRequestListener
{
protected $sc;
public function __construct(SecurityContextInterface $sc)
{
$this->sc = $sc;
}
public function onKernelRequest(GetResponseEvent $event)
{
if (HttpKernel::MASTER_REQUEST != $event->getRequestType()) {
// don't do anything if it's not the master request
return;
}
if( null === ($token = $this->sc->getToken()) ) {
// don't do anything if you are not behind a firewall
return;
}
// do anything with $token to get the user and check he is authenticated
$user = $token->getUser();
// Client IP
$ip = $event->getRequest()->getClientIp();
}
}
你的服务定义:
<!-- app/config/config.xml -->
<service id="kernel.listener.your_listener_name" class="Acme\DemoBundle\EventListener\AcmeExceptionListener">
<argument type="service" id="security.context" />
<tag name="kernel.event_listener" event="kernel.exception" method="onKernelException" />
</service>