使用cakephp在模型中使用会话变量

时间:2011-06-02 23:37:56

标签: session cakephp model authentication

无法找到一个看似简单问题的明确答案。

我使用find()从数据库中提取日期。我在Session变量(由Authentication提供)中有用户时区偏移量(-5,-6等)。我想在显示之前根据用户时区使用afterFind()回调来更新时间,然后在重新保存时使用beforeSave()回调调整回GMT。

如何访问模型中afterFind函数内的Auth变量?

谢谢!

1 个答案:

答案 0 :(得分:5)

由于Auth-Component是Controller的扩展,因此没有“自然”方式将其纳入您的模型。

您可以执行App::import('Controller', 'Users')或无论您在何处执行此操作。

您可以在此处查看如何使用此功能:Using App::import

但我真的认为,因为这只是显示一些信息的问题,助手将是解决问题的更好方法(在MVC中提供“V”)。

您可以编写一个帮助您记录日期的帮助程序(我认为您在数据库中使用DATEDATETIME)并将其转换为正确的时区。

function convert_timezone($time)
    $timezone = $this->Session->read('Auth.timezone');
    date_default_timezone_set($timezone); //set the correct timezone which we read from the Session
    return gmdate("M d Y H:i:s", strtotime($time)); //using strtotime to convert the time from the database to a timestamp
}

请查看这些通知链接,了解如何编写自己的帮助程序,函数gmdate和CakePHP中的Session Helper。

The methods of the session helper

Writing your own helpers

PHPs gmdate function