开发者

Using Session Variables inside a Model with cakephp

Having trouble finding a clear answer to a seemingly simple question.

I am pulling dates from a database using find(). I have the users timezone offset (-5, -6,开发者_StackOverflow中文版 etc) in the Session variables (provided by Authentication). I want to use an afterFind() callback to update the time according to the users timezone before displaying, and then a beforeSave() callback to adjust back to GMT when I resave it.

How do I access the Auth variables inside the afterFind function in the model?

Thanks!


Since the Auth-Component is an extension of the Controller there is no "natural" way of getting this into your model.

You could do an App::import('Controller', 'Users') or wherever you are doing this.

You can see how you can use this function here: Using App::import

But I really think, since this is just a matter of displaying some information a helper would be the better solution for your problem (to serve the "V" in MVC).

You could write a helper which takes your date (I'm thinking you are using either DATE or DATETIME in your database) and converts it to the correct timezone.

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
}

Please have a look at these informing links on how to write your own helper, the function gmdate and the Session Helper from CakePHP.

The methods of the session helper

Writing your own helpers

PHPs gmdate function

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜