使用Doctrine 1.2连接到MYSQL 5.1服务器的Zend Framework web应用程序。
大多数数据需要以当地时区输入和显示。因此,按照here的建议,我希望(我认为)将PHP和MySQL设置为使用UTC,然后在插入/更新之前将其转换为本地时间以进行显示和转换为UTC。如果这完全是愚蠢的,我很高兴听到一个更好的方法。
那么,我如何告诉Doctrine将MySQL会话设置为UTC?从本质上讲,我如何告诉Doctrine在打开连接时发出MySQL命令SET SESSION time_zone = 'UTC';?
提前感谢!
发布于 2010-11-26 16:43:37
这似乎可以通过使用postConnect()方法将Doctrine_EventListener附加到Doctrine_Connection对象来完成。
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。]
https://stackoverflow.com/questions/4282482
复制相似问题