我试图访问会话抛出不同的控制器或在一个控制器中的不同函数但是当我尝试访问来自不同函数的值时,变量为NULL 我阅读了一些文档(包括cakephp session cookbook)等等,但在使用之前我无法理解如何配置会话。
我在一个控制器中遇到一个问题,我试图使用一个会话,但是在我把它写在另一个函数后,该值为null?
我的另一个问题是如何避免写$ this-> request-> session();在我想要使用会话的每个功能中。 代码:
<?php
namespace App\Controller;
use App\Controller\AppController;
use App\Model\Entity\Answer;
use Cake\ORM\TableRegistry;
class ComlibsController extends AppController {
public function index() {
}
public function getResult(){
$this->viewBuilder()->layout('comlib'); //change the layout from default
$live_req = $this->request->data['searchBox']; // get the question
$session->write('comlib/question' , $live_req);
$query = $this->Comlibs->LFA($live_req); // get the first answer
$shown_answerID = array($query[0]['answers'][0]['id'], '2');
$this->Session->write(['avoidedID' => $shown_answerID]); //avoid the answer that user saw to repeat agian
$this->set('question',$query[0]['question']); // does work
//get the answers result
//and send the array to the
$fields = array('id','answer','rate' , 'view' , 'helpful');
for ($i = 0 ; $i <= 6 ; $i++) {
$this->set('id'.$i,$query[0]['answers'][$i][$fields[0]]);
$this->set('answer'.$i,$query[0]['answers'][$i][$fields[1]]);
$this->set('rate'.$i,$query[0]['answers'][$i][$fields[2]]);
$this->set('view'.$i,$query[0]['answers'][$i][$fields[3]]);
$this->set('helpful'.$i,$query[0]['answers'][$i][$fields[4]]);
}
}
public function moveon() {
$this->render('getResult');
$this->viewBuilder()->layout('comlib');
echo $question = $session->read('comlib/question'); // empty value echo
$avoidedIDs = $session->read('avoidedID');
var_dump($avoidedIDs); // returns NULL WHY ?
$theid = $this->request->here;
$query = $this->Comlibs->LFM($theid,$avoidedIDs,$question);
echo 'imcoming';
}
}
感谢Adnvanced
答案 0 :(得分:0)
答案 1 :(得分:0)
尝试
$this->session()->write('avoidedID', $shown_answerID);
而不是
$this->session()->write(['avoidedID' => $shown_answerID]);
然后尝试
$avoidedIDs = $this->session()->read('avoidedID');
而不是
$avoidedIDs = $session->read('avoidedID');