CI_controllerを拡張する独自のコントローラー(MY_cotrollerなど)を作成し、そこに共有コードを配置すると、3つのコントローラーが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();
}
}
これらは単なる例であり、もちろんこのようなものをエコーすることはありませんが、表示などに渡すことはできますが、説明には十分だと思います。誰かがより良いデザインを持っているかもしれませんが、これは私が数回使用したものです。