Symfony2:在何处设置用户定义的时区 [英] Symfony2: Where to set a user defined time zone
问题描述
对于当前项目,我的要求之一是允许用户为其帐户选择时区,然后将该时区用于整个网站中所有与日期/时间相关的功能.
One of my requirements for my current project is to allow a user to choose a time zone for their account, and then use this time zone for all date/time related features throughout the entire site.
我的看法有两种选择:
- 为每个新的DateTime将DateTimeZone对象传递给DateTime的构造函数
- 使用PHP的
date_default_timezone_set()
设置默认时区
- Pass in a DateTimeZone object to DateTime's constructor for every new DateTime
- Set the default time zone using PHP's
date_default_timezone_set()
使用date_default_timezone_set似乎是一种方法,但是我不确定应该在哪里设置.由于每个用户的时区会有所不同,并且整个网站都使用DateTime,因此我需要将其设置为某个会影响所有页面的地方.
It seems like using date_default_timezone_set is the way to go, but I'm not sure exactly where I should set it. Because the time zone will be different from user to user and DateTime's are used all over the site, I need to set it somewhere that it will affect all pages.
也许我可以编写一个事件监听器,以在成功登录后对其进行设置?如果我采用这种方法,它会在所有页面上保持设置还是仅在每页上设置?
Maybe I could write an event listener that sets it after a successful login? If I take this approach, will it stay set across all pages or is it only set on a per-page basis?
我很想听听其他人如何做到这一点.
I'd love to hear how others would approach this.
推荐答案
是的,您可以使用事件监听器来挂接kernel.request
事件.
Yea, you could use an event listener, hooking on the kernel.request
event.
这是我的一个项目中的侦听器:
Here is the listener from one of my projects:
<?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()}'");
}
}
这篇关于Symfony2:在何处设置用户定义的时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!