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

tni*_*ols 0 authentication session cakephp model

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

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

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

谢谢!

Tim*_*Tim 5

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

你可以做一个App::import('Controller', 'Users')或任何你这样做的地方.

您可以在此处查看如何使用此功能:使用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
}
Run Code Online (Sandbox Code Playgroud)

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

会话助手的方法

写自己的帮手

PHPs gmdate函数