2015-11-15 38 views
0

我正在使用Ion_Auth庫和Codeigniter 3.0。*。我設法在__construct()方法我Admin_Controller來顯示用戶的電子郵件,我登錄時使用此行代碼:設置用於存儲用戶電子郵件的變量而不重複每個功能中的代碼

$this->user_email = $this->ion_auth->user()->row(); 

但我需要重複這個代碼:

$data['user_email'] = $this->user_email->email; 

在每一個視圖方法在每個控制器內。我在我的header.php中顯示變量$user_email,這對每個頁面都是一樣的。我如何讓每個人都可以訪問它,而無需重複這一行代碼?

+0

'header.php'是一個視圖嗎? – DFriend

+0

@D朋友是的。 – mfgabriel92

回答

0

將類屬性$data添加到Admin_controller類定義中。 $ data屬性將可用於擴展Admin_controller的每個控制器。因爲它是一個類屬性,所以它的訪問語法爲$this->data

class Admin_controller extends CI_Controller 
{ 
    //our new class property 
    protected $data = array(); 

    public function __construct(){ 
     parent :: __construct(); 
     // do what is needed to get $ion_auth working 
    } 
} 

在延伸Admin_controller任何類在構造函數中設置$data['$user_email']。它隨後可被給出$這個 - >數據

class Some_controller extends Admin_controller 
{ 
    public function __construct(){ 
     parent :: __construct(); 
     //I am assuming that by this time $this->ion_auth->user() exists 
     //so we add a key and value to the class' $data property 
     //Note the use of the "$this->" syntax) 
     $this->data['user_email'] = $this->ion_auth->user()->row(); 
    } 

    public function sets_up_a_view(){ 
     //do stuff until you're ready for the header 
     //note that we are sending the class property "$this->data" to the view 
     $this-load->view('header', $this->data); 
     //load other views as needed using $this-data or other array - your choice 
    } 

    public function some_other_view(){ 
     //send class property to view 
     $this-load->view('header', $this->data); 
     $data['foo'] = 42; 
     //send local var to view 
     $this-load->view('other_parts', $data); 
    } 
} 

注意兩個sets_up_a_view()some_other_view()發送類屬性「$這個 - >數據」來header.php每個視圖。但在some_other_view()我們設置了一個名爲$data的本地變量,發送到other_parts.php視圖。

+0

這就是我所做的。我從我的'Admin_controller'的'__construct()'方法中調用'$ data'變量,該變量由我擁有的每個其他控制器擴展。這裏的問題是我必須重複這個'$ data ['user_email'] = $ this-> user_email-> email;'在每個調用我的視圖的方法中。我想知道是否有辦法避免重複它,但我認爲它不是? – mfgabriel92

+0

@ mfgabriel92,我修改了答案(我希望)使我的解決方案更加清晰。 – DFriend

+0

我找到了解決方案!檢查我自己的答案。無論如何,謝謝你。 – mfgabriel92

0

將該溶液在我Admin_controller加入這兩行代碼:

$data['user_email'] = $this->ion_auth->user()->row()->email; 
$this->load->vars($data); 

藉助於此,在延伸Admin_controller控制器每個視圖方法可以訪問此變量。

相關問題