このエントリーをはてなブックマークに追加

更新日: 2016年2月25日

実行時間: 0.0080

CI_Controller

 「CI_Controller」クラスは、ユーザが開発するコントローラクラスの基底クラスとなります。 ユーザが開発するコントローラクラスは必ず「CI_Controller」クラスを継承しなければいけません。

 「基礎編 / コントローラ」の頁も参照してください。

 「CI_Controller」クラスは「CodeIgniter.php」によって呼び出されると、「CodeIgniter.php」がそれまでにロードした コアクラスのインスタンスと、新たにロードした「CI_Loader」 クラスのインスタンスをプロパティ変数にセットして保持します。
 「CI_Controller」が保持する各コアクラスのインスタンスとプロパティ変数は以下のものとなります。

CI_Benchmark $this->benchmark
CI_Hooks $this->hooks
CI_Config $this->config
CI_Utf8 $this->utf8
CI_URI $this->uri
CI_Router $this->router
CI_Output $this->output
CI_Security $this->security
CI_Input $this->input
CI_Lang $this->lang
CI_Loader $this->load
 当然のことながら、上記のプロパティ変数と同名のプロパティ変数をユーザが開発するコントローラで定義することはできません

コアクラスの利用

 「CI_Controller」クラスを継承(オーバーライド)したコントローラクラスは、 これらのプロパティ変数を用いて対応するコアクラスの機能が利用できるようになります。
 以下は、それぞれのコアクラスインスタンスの機能を利用する一例です。

  • $this->benchmark
  • $this->benchmark->mark('my_mark_start');
  • $this->config
  • $this->config->load('my_config');
  • $this->utf8
  • $this->utf8->safe_ascii_for_xml($string);
  • $this->uri
  • $this->uri->segment(3);
  • $this->router
  • $this->router->fetch_class();
  • $this->output
  • $this->output->get_output();
  • $this->security
  • $this->security->get_csrf_token_name();
  • $this->input
  • $this->input->post('key');
  • $this->lang
  • $this->lang->load('greeting');
  • $this->load
  • $this->load->view('layout');

CI_Controllerクラスインスタンス取得

 「CI_Controller」及び「CI_Model」基底クラスを継承(オーバーライド)したクラスは、 各コアクラスインスタンスをプロパティ変数を用いることで利用できるのですが、 コントローラとモデル以外のライブラリクラスやヘルパークラスなどからは プロパティ変数を利用してコアクラスのインスタンスにアクセスできません。

 ライブラリクラスやヘルパークラスからコアクラスのインスタンスを利用するには、 「CI_Controller」クラスのインスタンスを取得する必要があります。
 取得した「CI_Controller」インスタンスからコアクラスのインスタンスが利用できるようになります。

CI_Controller::get_instance()

     「CI_Controller」クラスのスタティックメソッド「get_instance()」を実行すると、「CI_Controller」
    クラスのインスタンスが取得できます。
    「get_instance()」メソッドは、シングルトンと呼ばれるデザインパターンの手法で、「CI_Controller」 のインスタンスを返します。
     つまり、何度「get_instance()」を実行しても複数の「CI_Controller」インスタンスが作成されることは無く、 常に同じインスタンスを取得することができます。

    $CI = CI_Controller::get_instance();
    または、「CodeIgniter.php」で定義されている「CI_Controller::get_instance()」のラッパー関数からも
    取得できます。
    $CI =& get_instance();
  • CI_Controllerインスタンスの利用
  • $CI->config->load('my_config');