Cakephp 3 How to make session array

时光怂恿深爱的人放手 提交于 2019-12-08 04:19:31

问题


I am trying to write session in controller. My structure is

$_SESSION['a'][0] = 1;
$_SESSION['a'][1] = 2;
$_SESSION['a'][2] = 3;

And I am trying this

Configure::write('Session', ['a' =>'1'])

But it is not working. How do this in cakephp 3 way


回答1:


To write variable in Session in CakePHP 3 you need to write following code :

$this->request->session()->write('Your Key',Your_array);

To know more information you can visit here :

http://book.cakephp.org/3.0/en/development/sessions.html




回答2:


You can simply use

$session->write([
  'key1' => 'blue',
  'key2' => 'green',
]);

I am refering to

http://book.cakephp.org/3.0/en/development/sessions.html#reading-writing-session-data




回答3:


The answer is that this cannot be done in CakePHP 3.x

In vanilla PHP, it's possible to do this:

<?php
    session_start();
    $_SESSION['a'][0] = 1;
    $_SESSION['a'][1] = 2;
    $_SESSION['a'][2] = 3;
    var_dump($_SESSION);
?>

Which will output:

array(1) { 
    ["a"]=> array(3) { 
        [0]=> int(1) 
        [1]=> int(2) 
        [2]=> int(3) 
    } 
}

This is correct, and what should happen.

In CakePHP, you cannot specify arrays in the session key. For example:

$this->request->session()->write('a[]', 1);
$this->request->session()->write('a[]', 2);
$this->request->session()->write('a[]', 3);

Will not work.

If you remove the [] the value will get overwritten. For example:

$this->request->session()->write('a', 1);
$this->request->session()->write('a', 2);
$this->request->session()->write('a', 3);

The value of $this->request->session()->read('a') would be 3. The values 1 and 2 have been overwritten. Again, this is to be expected because you're overwriting the key a each time. The equivalent vanilla PHP for this is:

$_SESSION['a'] = 1;
$_SESSION['a'] = 2;
$_SESSION['a'] = 3;

Due to the lack of an indexed array, $_SESSION['a'] gets overwritten each time. This is normal behaviour. It needs to have the indexes (e.g. ['a'][0], ['a'][1], ...) to work!

The other answers where they have given things like key1 and key2 are not appropriate. Because there are many situations where you want everything contained within an indexed array. Generating separate key names is wrong for this type of scenario.



来源:https://stackoverflow.com/questions/39491196/cakephp-3-how-to-make-session-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!