CakePHP3 中的会话变量

Session variable in CakePHP3

当用户访问我的 website/app 时,我需要存储一些重要信息(分支 ID)。 此信息应该在每个控制器中可用。我所做的是:

AppController.php

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

FooController.php

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

我不确定这是否正确。这是一个会话变量还是只是一个配置?这个变量可以被其他用户覆盖吗?

我在 Cookbook 中读到的是,我可以使用:

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

然后读取任意控制器中的变量:

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

可是我在哪里可以设置'branch'呢?这在 AppController 中甚至可能吗?

Sessions is available 任何你可以访问请求对象的地方。

换句话说,把你的分支设置在你想要的地方(或者对你来说容易的地方)。 例如,我认为你最好这样做:.

在你的 App.php 中初始化 你的 "Branch" 值是这样的

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

在您的 AppController 中,在 beforeFilter 函数中检查会话是否存在,否则,使用这样的配置值

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

在你的 fooController 中只需使用 $this->request->session()->read('branch');$this->request->session()->write('branch', 'value');

但您也可以在 View 或 Cell 中读写会话...

希望对您有所帮助。