是的,您可以使用事件侦听器来挂钩kernel.request
事件。
这是我的一个项目中的听众:
<?php
namespace Vendor\Bundle\AppBundle\Listener;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Doctrine\DBAL\Connection;
use JMS\DiExtraBundle\Annotation\Service;
use JMS\DiExtraBundle\Annotation\Observe;
use JMS\DiExtraBundle\Annotation\InjectParams;
use JMS\DiExtraBundle\Annotation\Inject;
/**
* @Service
*/
class TimezoneListener
{
/**
* @var \Symfony\Component\Security\Core\SecurityContextInterface
*/
private $securityContext;
/**
* @var \Doctrine\DBAL\Connection
*/
private $connection;
/**
* @InjectParams({
* "securityContext" = @Inject("security.context"),
* "connection" = @Inject("database_connection")
* })
*
* @param \Symfony\Component\Security\Core\SecurityContextInterface $securityContext
* @param \Doctrine\DBAL\Connection $connection
*/
public function __construct(SecurityContextInterface $securityContext, Connection $connection)
{
$this->securityContext = $securityContext;
$this->connection = $connection;
}
/**
* @Observe("kernel.request")
*/
public function onKernelRequest()
{
if (!$this->securityContext->isGranted('ROLE_USER')) {
return;
}
$user = $this->securityContext->getToken()->getUser();
if (!$user->getTimezone()) {
return;
}
date_default_timezone_set($user->getTimezone());
$this->connection->query("SET timezone TO '{$user->getTimezone()}'");
}
}