Home » Php » php – Symfony2: Where to set a user defined time zone

php – Symfony2: Where to set a user defined time zone

Posted by: admin July 12, 2020 Leave a comment

Questions:

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.

How to&Answers:

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()}'");
    }
}