LoginSignup
4
4

More than 3 years have passed since last update.

CodeIgniterのget_instance()についてまとめた

Last updated at Posted at 2020-03-25

はじめに

今回新たに参画したプロジェクトでCodeIgniterが使われていたので勉強がてらまとめてみました。
フレームワークの中身を読んでいるとget_instance()にたどり着いたので今回はそれを題材にして記事にいたしました。

get_instance()

コントローラのメソッド内でインスタンス化されるクラスは全てCodeigniterのネイティブリソースにアクセスできます。
get_instance()関数を利用することによってシンプルに書くことが可能になります。

  • 返り値
    • コントローラのインスタンスへの参照
  • 返り値の型
    • CI_Controller
  • 関数の役割
    • メインのCodeIgniterオブジェクトを返す

通常、Codeigniterの利用可能なメソッドを呼び出すには$thisを使う必要があります。

$this->load->helper('url');
$this->load->library('session');
$this->config->library('base_url');

しかし$thisはそのコントローラ内、モデル内、 ビュー内にのみ機能するようになります。

独自のカスタムクラスからCodeigniterのクラスを使用したい場合は以下のようにします。
まず、変数にCodeigniterのオブジェクトを割り当てましょう。

$CI =& get_instance();

オブジェクトを変数に割り当てたのなら、$thisの代わりにその変数を使用します。

$CI =& get_instance();

$CI->load->helper('url');
$CI->load->library('session');
$CI->config->item('base_url');

もし別のクラス内でget_instance()を使うならプロパティに割り振ると良いですよ〜。

class Igniter {

    protected $CI;

    // コンストラクタでなくてもOKですが、
    // クラスが呼ばれた段階で実行されるのて楽なのでおすすめです。
    public function __construct()
    {
        // Codeigniterのスーパーオブジェクトを割り当てます。
        $this->CI =& get_instance();
    }

    public function foo()
    {
        $this->CI->load->helper('url');
        redirect();
    }

    public function bar()
    {
        $this->CI->config->item('base_url');
    }
}

プロパティに振らない場合は、

class Igniter {

    public function foo()
    {
        $CI =& get_instance(); // 1回目の呼び出し
        $CI->load->helper('url');
        redirect();
    }

    public function bar()
    {
        $CI =& get_instance(); // 2回目の呼び出し
        $CI->config->item('base_url');
    }
}

メソッドが増えるごとに呼び出さなければならないのでプロパティに振ることをお勧めです。

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4