简体   繁体   English

CakePHP3中的会话变量

[英]Session variable in CakePHP3

I need to store some vital information (branch ID) when a user visits my website/app. 用户访问我的网站/应用程序时,我需要存储一些重要信息(分支ID)。 This information should be available in every controller. 此信息应在每个控制器中可用。 What I do is this: 我的工作是这样的:

AppController.php AppController.php

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

FooController.php 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? 在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 在您的App.php 初始化 “ Branch”值,如下所示

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

In your AppController , inside beforeFilter function check if the session exists, otherwise, use the config value like this 在您的AppController beforeFilter函数内部,检查会话是否存在,否则,请使用类似config的值

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'); 在您的fooController只需使用$this->request->session()->read('branch'); and $this->request->session()->write('branch', 'value'); $this->request->session()->write('branch', 'value');

But you can also read and write the session inside View or Cell... 但是您也可以在View或Cell中读取和写入会话...

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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