2015-04-22 72 views
0

任務上調用視圖負載笨控制器功能

抓住用戶的從數據庫中每一個新的頁面負載均衡。無法在會話存儲是有獎金制度,而他是在記錄這會增加用戶的平衡

在我的網頁設置的方式,它有4個部分:

$this->load->view('head'); //Head, meta, css, js 
$this->load->view('navbar'); //Strip 50px height at top of page. Has navigation, logout and user balance 
$this->load->view('xxx'); //Unique page content 
$this->load->view('footer'); //standard footer 

我可以傳遞信息通過附加參數來查看:

$this->load->view('navbar', $balance); 

但是,這意味着每次調用頁面時,都必須從控制器的某處調用數據庫。

我在找的是如何實現的想法,因此每次調用navbar view時,它都會自動調用一個返回用戶餘額的控制器函數。

我想是這樣的:

$this->load->view('navbar', function getBalance() { 
    return callControllerAndGetBalance(); 
}); 

只好把在頁面加載調用控制器,然後更改值,但似乎只是錯誤的navbar一個AJAX調用的骯髒的想法。

任何想法?

+0

關斷主題的所有新用戶指南的笨2笨和3現在http://www.codeigniter.com/docs – user4419336

回答

2

你可以用CodeIgniter的鉤子:

https://ellislab.com/codeigniter/user-guide/general/hooks.html

未經檢驗的,但是這是我認爲它必須工作。從這個quora鏈接中,我輸入了評論,它看起來像當你調用$ controller = & get_instance();那麼這就是控制器,你可以添加一個屬性,它會在你的視圖中。

我會用不同的選項發揮好,這可能是有前途取決於你在__construct方法在做什麼:

post_controller_constructor 你的控制器實例化後立即調用,但在此之前發生任何方法調用。

class Blog extends CI_Controller{  

     public $balance = 0; 

     public function getBalance(){   
      $this->balance = Balance::getMe(); 
     } 
} 

你可以做的是從你的鉤子調用get_instance輔助函數。

class PostControllerHook{ 
     function post_controller($params) {  
      // $params[0] = 'controller' (given the params in the question)  
      // $controller is now your controller instance,  
      // the same instance that just handled the request  
      $controller =& get_instance();  
      $controller->getBalance(); 
     } 
} 

然後用

$this->load->view('navbar', $this->balance); 
+0

恐怕要問哪個鉤使用。我感覺post_controller可能是一個,但我真的不知道如何介入它。 – Alexey

+0

我還沒有真正做到這一點,儘管我已經使用了很多CodeIgniter。我猜實際上是相同的 - post_controller。原因是,你正在做一個非常簡單的操作,這只是一個附加。這裏有一個小例子:http://www.quora.com/Hooks-concept-in-codeigniter-with-simple-examples – dgig

+0

我對如何使用它的不確定性依然存在。我不知道如何將數據傳遞給視圖。 – Alexey