0 フォロワー

クラス yii\di\Instance

継承yii\di\Instance
利用可能バージョン2.0
ソースコード https://github.com/yiisoft/yii2/blob/master/framework/di/Instance.php

Instance は、依存性注入 (DI) コンテナまたはサービスロケータ内の名前付きオブジェクトへの参照を表します。

get() を使用して、$id が参照する実際のオブジェクトを取得できます。

Instance は主に次の 2 つの場所で使用されます。

  • 依存性注入コンテナを構成する場合、Instance を使用してクラス名、インターフェース名、またはエイリアス名を参照します。参照は後でコンテナによって実際のオブジェクトに解決できます。
  • 依存オブジェクトを取得するためにサービスロケータを使用するクラス内。

次の例は、Instance で DI コンテナを構成する方法を示しています。

$container = new \yii\di\Container;
$container->set('cache', [
    'class' => 'yii\caching\DbCache',
    'db' => Instance::of('db')
]);
$container->set('db', [
    'class' => 'yii\db\Connection',
    'dsn' => 'sqlite:path/to/file.db',
]);

また、次の例は、クラスがサービスロケータからコンポーネントを取得する方法を示しています。

class DbCache extends Cache
{
    public $db = 'db';

    public function init()
    {
        parent::init();
        $this->db = Instance::ensure($this->db, 'yii\db\Connection');
    }
}

公開プロパティ

継承されたプロパティを非表示

プロパティ タイプ 説明 定義元
$id string コンポーネント ID、クラス名、インターフェース名、またはエイリアス名 yii\di\Instance
$optional boolean 例外をスローする代わりに null を返す必要がある場合 yii\di\Instance

公開メソッド

継承されたメソッドを非表示

メソッド 説明 定義元
__set_state() var_export() を使用した後、クラスの状態を復元します。 yii\di\Instance
ensure() 指定された参照を実際のオブジェクトに解決し、指定された型であることを確認します。 yii\di\Instance
get() この Instance オブジェクトが参照する実際のオブジェクトを返します。 yii\di\Instance
of() 新しい Instance オブジェクトを作成します。 yii\di\Instance

保護されたメソッド

継承されたメソッドを非表示

メソッド 説明 定義元
__construct() コンストラクタ。 yii\di\Instance

プロパティの詳細

継承されたプロパティを非表示

$id 公開プロパティ

コンポーネント ID、クラス名、インターフェース名、またはエイリアス名

public string $id null
$optional 公開プロパティ

例外をスローする代わりに null を返す必要がある場合

public boolean $optional null

メソッドの詳細

継承されたメソッドを非表示

__construct() 保護されたメソッド

コンストラクタ。

protected void __construct ( $id, $optional false )
$id string

コンポーネント ID

$optional boolean

例外をスローする代わりに null を返す必要がある場合

                protected function __construct($id, $optional = false)
{
    $this->id = $id;
    $this->optional = $optional;
}

            
__set_state() public static メソッド (バージョン 2.0.12 から利用可能)

var_export() を使用した後、クラスの状態を復元します。

参照: https://www.php.net/manual/en/function.var-export.php

public static yii\di\Instance __set_state ( $state )
$state 配列
スロー yii\base\InvalidConfigException

$state プロパティに id パラメータが含まれていない場合

                public static function __set_state($state)
{
    if (!isset($state['id'])) {
        throw new InvalidConfigException('Failed to instantiate class "Instance". Required parameter "id" is missing');
    }
    return new self($state['id']);
}

            
ensure() public static メソッド

指定された参照を実際のオブジェクトに解決し、指定された型であることを確認します。

参照は、文字列または Instance オブジェクトとして指定できます。前者の場合、コンテナの種類に応じて、コンポーネント ID、クラス/インターフェース名、またはエイリアスとして扱われます。

コンテナを指定しない場合、このメソッドは最初に Yii::$app を試し、次に Yii::$container を試します。

例:

use yii\db\Connection;

// returns Yii::$app->db
$db = Instance::ensure('db', Connection::class);
// returns an instance of Connection using the given configuration
$db = Instance::ensure(['dsn' => 'sqlite:path/to/my.db'], Connection::class);
public static object ensure ( $reference, $type null, $container null )
$reference object|string|array|static

オブジェクトまたは目的のオブジェクトへの参照。コンポーネント ID または Instance オブジェクトの形式で参照を指定できます。バージョン 2.0.2 以降では、オブジェクトを作成するための設定配列を渡すこともできます。設定配列で "class" の値が指定されていない場合、$type の値が使用されます。

$type string|null

チェックするクラス/インターフェース名。null の場合、型チェックは実行されません。

$container yii\di\ServiceLocator|yii\di\Container|null

コンテナ。これは get() に渡されます。

戻り値 object

Instance が参照するオブジェクト。または、$reference がオブジェクトの場合は $reference 自体。

スロー yii\base\InvalidConfigException

参照が無効な場合

                public static function ensure($reference, $type = null, $container = null)
{
    if (is_array($reference)) {
        $class = isset($reference['class']) ? $reference['class'] : $type;
        if (!$container instanceof Container) {
            $container = Yii::$container;
        }
        unset($reference['class']);
        $component = $container->get($class, [], $reference);
        if ($type === null || $component instanceof $type) {
            return $component;
        }
        throw new InvalidConfigException('Invalid data type: ' . $class . '. ' . $type . ' is expected.');
    } elseif (empty($reference)) {
        throw new InvalidConfigException('The required component is not specified.');
    }
    if (is_string($reference)) {
        $reference = new static($reference);
    } elseif ($type === null || $reference instanceof $type) {
        return $reference;
    }
    if ($reference instanceof self) {
        try {
            $component = $reference->get($container);
        } catch (\ReflectionException $e) {
            throw new InvalidConfigException('Failed to instantiate component or class "' . $reference->id . '".', 0, $e);
        }
        if ($type === null || $component instanceof $type) {
            return $component;
        }
        throw new InvalidConfigException('"' . $reference->id . '" refers to a ' . get_class($component) . " component. $type is expected.");
    }
    $valueType = is_object($reference) ? get_class($reference) : gettype($reference);
    throw new InvalidConfigException("Invalid data type: $valueType. $type is expected.");
}

            
get() public メソッド

この Instance オブジェクトが参照する実際のオブジェクトを返します。

public object get ( $container null )
$container yii\di\ServiceLocator|yii\di\Container|null

参照されたオブジェクトを見つけるために使用されるコンテナ。null の場合、このメソッドは最初に Yii::$app を試し、次に Yii::$container を試します。

戻り値 object

この Instance オブジェクトによって参照される実際のオブジェクト。

                public function get($container = null)
{
    try {
        if ($container) {
            return $container->get($this->id);
        }
        if (Yii::$app && Yii::$app->has($this->id)) {
            return Yii::$app->get($this->id);
        }
        return Yii::$container->get($this->id);
    } catch (\Exception $e) {
        if ($this->optional) {
            return null;
        }
        throw $e;
    } catch (\Throwable $e) {
        if ($this->optional) {
            return null;
        }
        throw $e;
    }
}

            
of() public static メソッド

新しい Instance オブジェクトを作成します。

public static yii\di\Instance of ( $id, $optional false )
$id string

コンポーネント ID

$optional boolean

例外をスローする代わりに null を返す必要がある場合

戻り値 yii\di\Instance

新しい Instance オブジェクト。

                public static function of($id, $optional = false)
{
    return new static($id, $optional);
}