LoginSignup
16
21

More than 5 years have passed since last update.

自作クラスでCodeIgniterオブジェクトを使用する

Posted at

この記事はCodeIgniter Advent Calendar 2013 の 3 日目の記事です。

先日に続いて3記事目。3日坊主になるかどうかですね。

まだまだCodeIgniter Advent Calendar は募集中ですよ!

さて、今回の内容ですが、先日はライブラリの作成方法だったのですが、その途中にでてきたget_instance()というものを紹介しましょう。

public function __construct()
{
    $config =& get_config();
    ...
}

public function login()
{
    $CI =& get_instance();
    ...
}

この$config =& get_config()も大体似ています。

get_instance()についてはもちろん、ここに書いてあります。

$CI =& get_instance();

コントローラーでCodeIgniterオブジェクトに入ってるLoaderを使用したい場合は

public function __construct()
{
    $this->load->library('user_agent');
    ...
}

のようにします。

しかし、ライブラリやヘルパーなど、自作したクラスでCodeIgniterオブジェクトを使用したい場合、単純に$thisでは取得できないです。(CI_Controllerを継承していないので、そらそうだ

このようなとき、CodeIgniterではシステムクラスをライブラリ内で明示的にロードする必要が生じます。

そのロードをするためにCodeIgniterのインスタンスを取得するのがget_instance()となります。

また、インスタンスを取得しただけではダメで、そのインスタンスを直接的に変更することも必要となる場合がありオブジェクトは必ず参照渡しで使用することが必要です。

これにより、CodeIgniterオブジェクトのオリジナルを使用することができます。

Example

例えば、universal_helper.phpというヘルパーを作成し、(./application/helpers/universal_helper.php

その中に、UserAgentから判別したis_mobile()というuser_agentクラスのラッパーメソッドを作成するとします。

これはダメ

if (!function_exists('is_mobile'))
{
    function is_mobile()
    {
        $this->load->library('user_agent');
        return $this->agent->is_mobile();
    }
}

こうする

if (!function_exists('is_mobile'))
{
    function is_mobile()
    {
        $CI =& get_instance();
        $CI->load->library('user_agent');
        return $CI->agent->is_mobile();
    }
}

こういった感じです。

どこで定義されている?

このget_instance()がどこで定義されているかと言うと、./system/core/CodeIgniter.php内で

// Load the base controller class
require BASEPATH.'core/Controller.php';

function &get_instance()
{
    return CI_Controller::get_instance();
}

のように定義されています。

そのため、基はシステムのコントローラーの./system/core/Controller.phpに下記のように定義されています。

public static function &get_instance()
{
    return self::$instance;
}

静的なinstanceという変数に格納されており、

private static $instance;

/**
 * Constructor
 */
public function __construct()
{
    self::$instance =& $this;

    // Assign all the class objects that were instantiated by the
    // bootstrap file (CodeIgniter.php) to local class variables
    // so that CI can run as one big super object.
    foreach (is_loaded() as $var => $class)
    {
        $this->$var =& load_class($class);
    }

    $this->load =& load_class('Loader', 'core');

    $this->load->initialize();

    log_message('debug', "Controller Class Initialized");
}

必要なクラスを含んでおります。

終わり

ちょっとコアっぽい話ですね。でも、しっかりとドキュメントには書いてあります。

次回のCodeIgniter Advent Calendar2013

明日、何書こう…

16
21
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
16
21