2011-04-10 118 views
3

我用代碼點火器是新手,目前我正在建立自己的用戶系統。我很遺憾地登錄過程,並且已經實現了一個用戶當前是否登錄的檢查。笨用戶登錄檢查

在我的頭,然後我想顯示一個鏈接到「註銷」,如果他們已經登錄,或「登錄」如果他們沒有在當前登錄。

我有一個工作功能在我的索引控制器如下,在$ loginstatus變量發送到我的網頁標題觀點:$ loginstatus不

function check_session() 
{ 
    //Check session status 

      $session = $this->session->userdata('login_state'); 

      $default = "Log In"; 

      if ($session == 1) 
      { 
       $url = site_url('index.php/users/logout'); 
       $status = "Log Out"; 



      } 
      else 
      { 
       $url = site_url('index.php/users/login'); 
       $status = $default; 
      } 

     $loginstatus = array(
         "url" => $url, 
         "status" => $status 
         ); 

     return $loginstatus; 
} 

因爲它是目前唯一索引控制器爲其他頁面的標題視圖生成,這是我的問題。

我會在哪裏把這個功能,所以它總是我的頭之前加載?我試圖創建一個與'普通'類的庫,然後自動加載,但我最終有很多問題。

在此先感謝。

回答

8

如果您正在使用CI版本波紋管2.0,然後創建新的應用類/庫/ MY_Controller.php,否則在應用/核心/ MY_Controller.php和所有應用程序控制器應該從其擴展。在這個類的__construct方法中,您將檢查登錄狀態並將其發送到視圖。

 
class MY_Controller extends CI_Controller 
{ 
    public function __construct() 
    { 
     parent::__construct(); 

     //Get the status which is array 
     $login_status = $this->check_session(); 

     //Send it to the views, it will be available everywhere 

     //The "load" refers to the CI_Loader library and vars is the method from that library. 
     //This means that $login_status which you previously set will be available in your views as $loginstatus since the array key below is called loginstatus. 
     $this->load->vars(array('loginstatus' => $login_status)); 
    } 

    protected function check_session() 
    { 
     //Here goes your function 
    } 
} 

另外,還要確保您的應用程序控制器從這個類

 
//application/controllers/index.php 

class Index extends MY_Controller 
{ 
    public function __construct() 
    { 
     parent::__construct(); 
    } 
} 

延長在你的意見,你可以這樣做:? < A HREF =」 < PHP的echo $ loginstatus [ '鏈接']; ?>「> < PHP的echo $ loginstatus [ '狀態']; ? > </a >

這可能會導致CI_Loader vars()方法正在執行傳遞給它的參數extract

+0

我想我明白你的意思,但我對'MY_Controller'有困難我以前試過使用這個,但是當我這樣做時我得到以下錯誤: ** bold **致命錯誤:類'MY_Controller'not在/home/chimeri1/public_html/application/controllers/welcome.php發現第3行** **大膽 – James 2011-04-10 19:56:43

+0

我使用CodeIgnitier 2.0順便說一下,謝謝你的幫助。 – James 2011-04-10 19:58:14

+0

更新:我有MY_Controller工作(我把它放在系統/核心,而不是應用程序/核心!),但我不認爲你的第二行關於發送變量的意見是爲我工作,你能解釋這是怎麼回事作品?謝謝。 – James 2011-04-10 20:18:52