2011-11-24 46 views
7

讓說我叫控制器時,我有很多方法,如 get_book();read_book();remove_book();笨 - 如何檢查會議在每一個方法

類中的任何方法可以在沒有用戶使用登錄後,我可以從會話中獲得user_id

我的問題是,什麼是最好的方法來檢查user_id會話是否設置,以便我可以使用這些方法?

至於現在我想建立一個is_logged_in()方法,並將其與if-else語句適用於每一個方法,如

if($this->is_logged_in() 
{ 
    //do something 
} 
else 
{ 
    //redirect to home 
} 

是不是很漫長而乏味?有沒有最終的方法來實現這一目標?

我讀的鏈接

codeigniter check for user session in every controller

但似乎還是有在每一個方法來應用is_logged_in檢查。

謝謝你幫助我!

回答

11

創建一個名爲MY_controller.php(前綴可以在配置文件中編輯)在/application/core文件:

<?php if (! defined('BASEPATH')) exit('No direct script access allowed'); 

class MY_Controller extends CI_Controller { 


    function __construct() 
    { 

     parent::__construct(); 

     //Initialization code that affects all controllers 
    } 

} 


class Public_Controller extends MY_Controller { 

    function __construct() 
    { 
     parent::__construct(); 

     //Initialization code that affects Public controllers. Probably not much needed because everyone can access public. 
    } 

} 

class Admin_Controller extends MY_Controller { 

    function __construct() 
    { 
     parent::__construct(); 
     //Initialization code that affects Admin controllers I.E. redirect and die if not logged in or not an admin 
    } 

} 

class Member_Controller extends MY_Controller { 

    function __construct() 
    { 
     parent::__construct(); 

     //Initialization code that affects Member controllers. I.E. redirect and die if not logged in 
    } 

} 

然後,無論何時您創建新控制器,您都可以決定需要什麼訪問權限

class Book extends Member_Controller { 

     //Code that will be executed, no need to check anywhere if the user is logged in. 
     //The user is guaranteed to be logged in if we are executing code here. 

//If you define a __construct() here, remember to call parent::__construct(); 
    } 

這很大程度上減少了代碼重複,因爲如果您需要除Book以外的其他成員控制器,則只需擴展Member_Controller即可。而不是必須在他們所有人中進行檢查。

+0

我明白你的答案,這是真的遵循DRY並幫助我將正確的業務規則應用於不同的用戶組。非常感謝您和@Kemal Kernal的幫助:) – user826224

9

你不一定需要那樣做。只需將登錄檢查代碼放入構造函數中,即可完成設置!

class Book extends CI_Controller 
{ 
    public function __construct() 
    { 
     if ($this->is_logged_in()) 
     { 
      // redirect to home 
     } 
    } 

    public function get_book() 
    { 
     ... 
    } 

    // The rest of the code... 
} 
+0

非常感謝你,我測試過,它完美無瑕。要從鏈接更新,我們應該把MY_Controller放在application/core下。再次感謝您的幫助:)祝您有美好的一天! – user826224

+2

@ user826224,你仍然需要用這個複製代碼。我的答案與你鏈接的答案有很大的不同,你應該仔細閱讀:) – Esailija

0

可以在控制器的構造函數中使用的方法,如:

 
if (! $this->session->userdata('logged_in')) 
    { 
      redirect('login'); 
    }