2015-05-20 65 views
1

所有代碼在一個控制器中如何在cakephp 3.0中刪除會話?

我的代碼是這樣的。

public function login() 
    { 
    $session = $this->request->session(); 
    $session_event_id = $session->read('Events.event_id'); 
    $session_division_id = $session->read('Events.division_id'); 

    if(!$session_event_id || !$session_division_id) { 
     $event_table = TableRegistry::get('Events'); 
     $event = $event_table->find('all', ['fields' => ['id'], 'order' => 'id desc'])->first(); 
     $session->write('Events.event_id', $event->id); 
     $session_event_id = $session->read('Events.event_id'); 

     $division_table = TableRegistry::get('Divisions'); 
     $division = $division_table->find('all',['fields' => ['id'], 'conditions' => ['event_id' => $event->id]])->first(); 
     $session->write('Events.division_id', $division->id); 
     $session_division_id = $session->read('Events.division_id'); 
    } 
    } 

通過上面的代碼,我能夠寫入和讀取會話值,但同時註銷我想刪除這些會話數據

public function logout() 
{  
    $session = $this->request->session(); 
    $this->$session->delete(); 
    return $this->redirect($this->Auth->logout()); 
} 

Warning (4096): Object of class Cake\Network\Session could not be converted to string [APP/Controller/UsersController.php, line 56]

Notice (8): Object of class Cake\Network\Session to string conversion [APP/Controller/UsersController.php, line 56]

Error: Call to a member function delete() on a non-object File /var/www/html/MEX/src/Controller/UsersController.php

+0

如果您收到錯誤,請即使它們非常基本,請始終發佈_complete_,_exact_錯誤消息,包括可能的堆棧跟蹤! – ndm

+0

我已經明確提到可以退出的錯誤 –

+3

注意在註銷時調用會話的delete()。你有'$ this - > $ session-> delete()'而不是'$ session-> delete()' – Eagle

回答

6

您正在尋找$this->request->session()->destroy();

http://book.cakephp.org/3.0/en/development/sessions.html#destroying-the-session

只是一個提示 - 沒有太多的點存儲一個變量爲$session的函數很小,其中$session的重用不是必需的。我將$this->request->session();存儲在一個變量中的唯一情況是,當我正在訪問會話以進行多次讀取和寫入所有相同的函數時。

(至於誤差而言,@Eagle是,你引用通過使用存儲變量的「$this」兩次正確的。)

3

感謝您的支持和幫助下終於找到我我自己的問題的解決方案

$session = $this->request->session(); 
    $session->delete('Events.event_id'); 
    $session->delete('Events.division_id'); 

通過這樣做,我能夠清除會話數據。謝謝