开发者

CakePHP Session variable use in view page?

开发者 https://www.devze.com 2022-12-08 20:20 出处:网络
I have a variable contaning \"username\" and want to get these values via session to any of the view pages.

I have a variable contaning "username" and want to get these values via session to any of the view pages.

How can I get this session variable in the开发者_如何学运维 view ?


There's a SessionComponent available in your Controller that you can use like $this->Session->write('Name', 'Value');. Analogously there's also the SessionHelper for the View, which does very similar things and can be used like $session->read('Name');.


You can use $this->Session->read('myParam') in your Views files.
But you can't use $this->Session->write('myParam').

As noted here:

The major difference between the Session Helper and the Session Component is that the helper does not have the ability to write to the session.


To use it in a helper you must remember to include it in your $helpers declaration:

class Foo extends AppHelper
{
    var $helpers = array('Session','Bar');


If you're in the controller, use the Session component. It's included, by default, in all the controllers. It has the Session::read() and Session::write() methods. Check out http://book.cakephp.org/view/173/Sessions for more information.

I believe, if the Session component is like some of the other components, you can use it inside the views. Try just doing $session->read() in your view code blocks. If that doesn't work, try doing a $this->Session->read(...). As a last resort, if none of those work, you can always use the good old PHP $_SESSION, although it's kinda veering outside the Cake framework. However, if you are sure you're not going to use Cake's Session management (and you don't really have to, IMO, as it's little more than a wrapper around $_SESSION), then just know when to properly apply the hack.


User this in you App controller's before filter

$this->Session->write('Person.eyeColor', 'username'); $green = $this->Session->read('Person.eyeColor'); $this->set('username',$green);

This will give you result as you want


You can pass the Session object from controller to a view template using

$this->set('session',$this->Session);

Then in view file use $session->read('SessionName');

0

精彩评论

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

关注公众号