您可以创建自己的控制器(例如 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();
}
}
这些只是例子,当然你不会回显这样的东西,而是将它传递给视图等,但我希望它足以说明。也许有人有更好的设计,但这是我用过几次的。