2012-08-17 186 views
0

我把下面的代碼放在public function index()的每個控制器中。截至目前,我有3個控制器,它會增加,直到我的網站完成。我需要下面所有頁面的代碼(即視圖)。把代碼放在codeigniter中的位置

$type = $this->input->post('type'); 
$checkin = $this->input->post('sd'); 
$checkout = $this->input->post('ed'); 

我的問題是我在哪裏可以把上面的代碼中只有一個位置,所以這將是適用於所有的網頁(即視圖),並避免把它在每個控制器。

回答

0

您可以創建自己的控制器(例如MY_cotroller)來擴展CI_controller,並在其中放置共享代碼,然後您的三個控制器應該擴展MY_controller。 然後,您可以隨時隨地調用它(或者如果您需要它,甚至可以將它放到構造函數中)。

這是我答應的樣品(假設你有默認設置的CodeIgniter)

核心文件夾中創建名爲MY_Controller.php

class MY_Controller extends CI_Controller{ 

    protected $type; 
    protected $checkin; 
    protected $checkout; 

    protected $bar; 

    public function __construct() 
    { 
     parent::__construct(); 
     $this->i_am_called_all_the_time(); 
    } 

    private function i_am_called_all_the_time() { 
     $this->type = $this->input->post('type'); 
     $this->checkin = $this->input->post('sd'); 
     $this->checkout = $this->input->post('ed'); 
    } 

    protected function only_for_some_controllers() { 
     $this->bar = $this->input->post('bar'); 
    } 

    protected function i_am_shared_function_between_controllers() { 
     echo "Dont worry, be happy!"; 
    } 
} 

然後在控制器的文件夾中創建您的控制器文件

class HelloWorld extends MY_Controller { 

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

    public function testMyStuff() { 
     // you can access parent's stuff (but only the one that was set), for example: 
     echo $this->type; 

     //echo $this->bar; // this will be empty, because we didn't set $this->bar 
    } 

    public function testSharedFunction() { 
     echo "some complex stuff"; 
     $this->i_am_shared_function_between_controllers(); 
     echo "some complex stuff"; 
    } 
} 

然後例如,另一個控制器:

class HappyGuy extends MY_Controller { 

    public function __construct() { 
     parent::__construct(); 
     $this->only_for_some_controllers(); // reads bar for every action 
    } 

    public function testMyStuff() { 
     // you can access parent's stuff here, for example: 
     echo $this->checkin; 
     echo $this->checkout; 

     echo $this->bar; // bar is also available here 
    } 

    public function anotherComplexFunction() { 
     echo "what is bar ?".$this->bar; // and here 
     echo "also shared stuff works here"; 
     $this->i_am_shared_function_between_controllers(); 
    } 
} 

這些僅僅是例子,當然你不會迴應這樣的東西,但通過它來查看等,但我希望它足以說明。也許有人會用更好的設計,但這是我用過的幾次。

+0

您好,我是新來的笨,我不知道如何實現代碼。可能是一個示例代碼會有所幫助。謝謝 – jaypabs 2012-08-17 06:06:21

+0

可悲的是我從手機上寫這個,所以很難,但是如果你搜索'擴展ci_controller',它應該引導你完成這一步。 – KadekM 2012-08-17 06:09:37

+0

然後,每個控制器只擴展MY_Controller。對不起,但不能進一步幫助。如果以後沒有答案,我會很樂意發佈示例代碼。 – KadekM 2012-08-17 06:09:58

0

如果你有例如主視圖文件,你需要的代碼的每個頁面上,那麼我建議你把主視圖文件(查看/ index.php文件)

我認爲,隨着@KadekM答案,你應該每次在每個控制器中調用一個函數,因爲你傷心,你想要在每個控制器中的這個代碼每個函數。

0

id建議將其添加到庫中,然後自動加載庫,以便網站上的每個頁面都可以訪問相同的庫。

爲自動加載reffer:autoload in codeigniter

相關問題