dongyou26216708
dongyou26216708
2012-05-22 00:24

Symfony2:在何处设置用户定义的时区

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.

The way I see it, I have two options:

  • 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()

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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dongsha7215 dongsha7215 9年前

    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()}'");
        }
    }
    
    点赞 评论 复制链接分享

为你推荐