2010-11-26 107 views
1

得到了Zend Framework Web应用程序使用Doctrine 1.2连接到MYSQL 5.1服务器。设置MySQL会话变量 - 时区 - 使用Doctrine 1.2和Zend Framework

大部分数据需要输入并显示在本地时区。因此,遵循here的建议,我想(我认为)将PHP和MySQL设置为使用UTC,然后在插入/更新之前处理显示和UTC显示的本地时间转换。 [如果这是完全愚蠢的,我很高兴地听到一个更好的办法。]

所以,我怎么告诉主义到MySQL会话设置为UTC?从本质上讲,如何告诉Doctrine在打开连接时发出MySQL命令SET SESSION time_zone = 'UTC';

提前致谢!

+0

你会考虑用`--timezone = UTC`来启动mysql吗? http://dev.mysql.com/doc/refman/5.1/en/time-zone-support.html?否则,您需要查找http://www.doctrine-project.org/api/orm/1.2/doctrine/doctrine_query.html。 – ajreal 2010-11-26 05:17:19

回答

2

看起来这可以通过使用postConnect()方法附加到Doctrine_Connection对象Doctrine_EventListener来完成。

Doctrine ORM for PHP - Creating a New Listener

喜欢的东西:

class Kwis_Doctrine_EventListener_Timezone extends Doctrine_EventListener 
{ 
    protected $_timezone; 

    public function __construct($timezone = 'UTC') 
    { 
     $timezone = (string) $timezone; 
     $this->_timezone = $timezone; 
    } 

    public function postConnect(Doctrine_Event $event) 
    { 
     $conn = $event->getInvoker(); 
     $conn->execute(sprintf("SET session time_zone = '%s';", $this->_timezone)); 
    } 
} 

[使用sprintf()这里可能是业余的,但我无法弄清楚如何做一个适当的参数绑定。 (不好意思的笑脸)

然后在我的应用程序的Bootstrap.php,我有这样的事情:

protected function _initDoctrine() 
{ 
    // various operations relating to autoloading 
    // .. 

    $doctrineConfig = $this->getOption('doctrine'); 

    $manager = Doctrine_Manager::getInstance(); 
    // various boostrapping operations on the manager 
    // .. 

    $conn = Doctrine_Manager::connection($doctrineConfig['dsn'], 'doctrine'); 
    // various boostrapping operations on the connection 
    // .. 

    // Here's the good stuff: Add the EventListener 
    $conn->addListener(new Kwis_Doctrine_EventListener_Timezone()); 

    return $conn; 
} 

[一个稍微题外话注:我的本地开发机器上,我不停地奔跑到MySQL错误我没有进入任何时区似乎被接受。原来,标准的MySQL安装会创建mysql数据库中的所有时区表,但实际上并未填充它们;你需要分别填充它们。更多信息在MySQL site。]