您可以創建自己的控制器(例如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();
}
}
這些僅僅是例子,當然你不會迴應這樣的東西,但通過它來查看等,但我希望它足以說明。也許有人會用更好的設計,但這是我用過的幾次。
您好,我是新來的笨,我不知道如何實現代碼。可能是一個示例代碼會有所幫助。謝謝 – jaypabs 2012-08-17 06:06:21
可悲的是我從手機上寫這個,所以很難,但是如果你搜索'擴展ci_controller',它應該引導你完成這一步。 – KadekM 2012-08-17 06:09:37
然後,每個控制器只擴展MY_Controller。對不起,但不能進一步幫助。如果以後沒有答案,我會很樂意發佈示例代碼。 – KadekM 2012-08-17 06:09:58