简体   繁体   中英

Session variable in CakePHP3

I need to store some vital information (branch ID) when a user visits my website/app. This information should be available in every controller. What I do is this:

AppController.php

Configure::write('branch',$id);

FooController.php

$branchId = Configure::read('branch');

I'm not sure if this is the right way. Is this a session variable or just a config? Can this variable be overwritten by other users?

What I read in the Cookbook was, that I can use:

Configure::write('Session', [
    'defaults' => 'php'
]);

and then read the variable in any controller:

$this->request->session()->read('branch');

But where can I set 'branch'? Is this even possible in AppController?

Sessions is available everywhere you have access to the request object.

In other words, set your branch where you want (or where it's easy for you). For example, I think it's better for you to do something like this:.

In your App.php initialise your "Branch" value like this

Configure::write('branch',$id);

In your AppController , inside beforeFilter function check if the session exists, otherwise, use the config value like this

if(!$this->request->session()->read('branch')){
    $this->request->session()->write('branch', Configure::read('branch'));
}

And in your fooController just use $this->request->session()->read('branch'); and $this->request->session()->write('branch', 'value');

But you can also read and write the session inside View or Cell...

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM