0 フォロワー

クラス yii\console\controllers\FixtureController

継承yii\console\controllers\FixtureController » yii\console\Controller » yii\base\Controller » yii\base\Component » yii\base\BaseObject
実装yii\base\Configurableyii\base\ViewContextInterface
使用するトレイトyii\test\FixtureTrait
利用可能なバージョン2.0
ソースコード https://github.com/yiisoft/yii2/blob/master/framework/console/controllers/FixtureController.php

フィクスチャデータの読み込みとアンロードを管理します。

#load fixtures from UsersFixture class with default namespace "tests\unit\fixtures"
yii fixture/load User

#also a short version of this command (generate action is default)
yii fixture User

#load all fixtures
yii fixture "*"

#load all fixtures except User
yii fixture "*, -User"

#load fixtures with different namespace.
yii fixture/load User --namespace=alias\my\custom\namespace\goes\here

unload サブコマンドは、フィクスチャのアンロードと同様に使用できます。

公開プロパティ

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

プロパティ 説明 定義元
$action yii\base\Action|null 現在実行中のアクション。 yii\base\Controller
$behaviors yii\base\Behavior[] このコンポーネントにアタッチされているビヘイビアのリスト。 yii\base\Component
$color boolean|null 出力でANSIカラーを有効にするかどうか。 yii\console\Controller
$defaultAction string コントローラのデフォルトアクションID。 yii\console\controllers\FixtureController
$fixtures yii\test\Fixture[] 現在のテストケースのロード済みのフィクスチャ。 yii\test\FixtureTrait
$globalFixtures array 読み込みとアンロード時に適用されるグローバルフィクスチャ。 yii\console\controllers\FixtureController
$help boolean 現在のコマンドに関するヘルプ情報を表示するかどうか。 yii\console\Controller
$helpSummary string yii\console\Controller
$id string このコントローラのID。 yii\base\Controller
$interactive boolean コマンドを対話的に実行するかどうか。 yii\console\Controller
$layout string|null|false このコントローラのビューに適用されるレイアウトの名前。 yii\base\Controller
$module yii\base\Module このコントローラが属するモジュール。 yii\base\Controller
$modules yii\base\Module[] このコントローラが配置されているすべての祖先モジュール。 yii\base\Controller
$namespace string フィクスチャを検索するデフォルトの名前空間。 yii\console\controllers\FixtureController
$passedOptionValues array 渡されたオプションに対応するプロパティ。 yii\console\Controller
$passedOptions array 実行中に渡されたオプションの名前。 yii\console\Controller
$request yii\base\Request|array|string リクエスト。 yii\base\Controller
$response yii\base\Response|array|string レスポンス。 yii\base\Controller
$route string 現在のリクエストのルート(モジュールID、コントローラID、アクションID)。 yii\base\Controller
$silentExitOnException boolean|null trueの場合、例外発生時に`ExitCode::OK`でスクリプトを終了します。 yii\console\Controller
$uniqueId string モジュールID(存在する場合)を接頭辞として付けたコントローラID。 yii\base\Controller
$view yii\base\View|yii\web\View ビューまたはビューファイルをレンダリングするために使用できるビューオブジェクト。 yii\base\Controller
$viewPath string このコントローラのビューファイルを含むディレクトリ。 yii\base\Controller

公開メソッド

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

メソッド 説明 定義元
__call() クラスメソッドではない名前付きメソッドを呼び出します。 yii\base\Component
__clone() このメソッドは、既存のオブジェクトをクローンしてオブジェクトが作成された後に呼び出されます。 yii\base\Component
__construct() yii\base\Controller
__get() コンポーネントプロパティの値を返します。 yii\base\Component
__isset() プロパティが設定されているかどうか(つまり、定義されていてnullではないかどうか)を確認します。 yii\base\Component
__set() コンポーネントプロパティの値を設定します。 yii\base\Component
__unset() コンポーネントプロパティをnullに設定します。 yii\base\Component
actionLoad() 指定されたフィクスチャデータを読み込みます。 yii\console\controllers\FixtureController
actionUnload() 指定されたフィクスチャをアンロードします。 yii\console\controllers\FixtureController
actions() コントローラに対して外部アクションを宣言します。 yii\base\Controller
afterAction() このメソッドは、アクションが実行された直後に呼び出されます。 yii\base\Controller
ansiFormat() ANSIコードで文字列をフォーマットします。 yii\console\Controller
attachBehavior() このコンポーネントにビヘイビアをアタッチします。 yii\base\Component
attachBehaviors() コンポーネントにビヘイビアのリストをアタッチします。 yii\base\Component
beforeAction() このメソッドは、アクションが実行される直前に呼び出されます。 yii\console\Controller
behaviors() このコンポーネントが動作するビヘイビアのリストを返します。 yii\base\Component
bindActionParams() パラメータをアクションにバインドします。 yii\console\Controller
canGetProperty() プロパティを読み取ることができるかどうかを示す値を返します。 yii\base\Component
canSetProperty() プロパティを設定できるかどうかを示す値を返します。 yii\base\Component
className() このクラスの完全修飾名を返します。 yii\base\BaseObject
confirm() yまたはnを入力してユーザーに確認を求めます。 yii\console\Controller
createAction() 指定されたアクションIDに基づいてアクションを作成します。 yii\base\Controller
detachBehavior() コンポーネントからビヘイビアをデタッチします。 yii\base\Component
detachBehaviors() コンポーネントからすべてのビヘイビアをデタッチします。 yii\base\Component
ensureBehaviors() behaviors()で宣言されたビヘイビアがこのコンポーネントにアタッチされていることを確認します。 yii\base\Component
findLayoutFile() 適用可能なレイアウトファイルを見つけます。 yii\base\Controller
fixtures() 現在のテストケースに必要なフィクスチャを宣言します。 yii\test\FixtureTrait
getActionArgsHelp() アクションの匿名引数に関するヘルプ情報を返します。 yii\console\Controller
getActionHelp() 指定されたアクションの詳細なヘルプ情報を返します。 yii\console\Controller
getActionHelpSummary() 指定されたアクションを記述する1行の短い概要を返します。 yii\console\Controller
getActionOptionsHelp() アクションのオプションに関するヘルプ情報を返します。 yii\console\Controller
getBehavior() 名前付きのビヘイビアオブジェクトを返します。 yii\base\Component
getBehaviors() このコンポーネントにアタッチされているすべてのビヘイビアを返します。 yii\base\Component
getFixture() 名前付きのフィクスチャを返します。 yii\test\FixtureTrait
getFixtures() globalFixtures()fixtures() で指定されたフィクスチャオブジェクトを返します。 yii\test\FixtureTrait
getHelp() このコントローラのヘルプ情報を返します。 yii\console\Controller
getHelpSummary() このコントローラを記述する1行の短い概要を返します。 yii\console\Controller
getModules() このコントローラのすべての祖先モジュールを返します。 yii\base\Controller
getOptionValues() アクションIDのオプションに対応するプロパティを返します。子クラスは、このメソッドをオーバーライドして可能なプロパティを指定できます。 yii\console\Controller
getPassedOptionValues() 渡されたオプションに対応するプロパティを返します。 yii\console\Controller
getPassedOptions() 実行中に渡された有効なオプションの名前を返します。 yii\console\Controller
getRoute() 現在のリクエストのルートを返します。 yii\base\Controller
getUniqueId() コントローラのユニークIDを返します。 yii\base\Controller
getView() ビューまたはビューファイルをレンダリングするために使用できるビューオブジェクトを返します。 yii\base\Controller
getViewPath() このコントローラのビューファイルを含むディレクトリを返します。 yii\base\Controller
globalFixtures() 異なるテストケースで共有が必要なフィクスチャを宣言します。 yii\test\FixtureTrait
hasEventHandlers() 名前付きイベントにハンドラがアタッチされているかどうかを示す値を返します。 yii\base\Component
hasMethod() メソッドが定義されているかどうかを示す値を返します。 yii\base\Component
hasProperty() このコンポーネントのプロパティが定義されているかどうかを示す値を返します。 yii\base\Component
init() オブジェクトを初期化します。 yii\base\Controller
initFixtures() フィクスチャを初期化します。 yii\test\FixtureTrait
isColorEnabled() ANSIカラーが有効かどうかを示す値を返します。 yii\console\Controller
loadFixtures() 指定されたフィクスチャをロードします。 yii\test\FixtureTrait
needToApplyAll() すべてのフィクスチャを適用する必要があるかどうかをチェックします。 yii\console\controllers\FixtureController
notifyNothingToLoad() 入力条件に従ってロードするフィクスチャがないことをユーザーに通知します。 yii\console\controllers\FixtureController
notifyNothingToUnload() 入力条件に従ってアンロードするフィクスチャがないことをユーザーに通知します。 yii\console\controllers\FixtureController
off() このコンポーネントから既存のイベントハンドラをデタッチします。 yii\base\Component
on() イベントにイベントハンドラをアタッチします。 yii\base\Component
optionAliases() オプションのエイリアス名を返します。 yii\console\controllers\FixtureController
options() アクション(id)の有効なオプションの名前を返します。オプションには、オプション名と同じ名前のパブリックメンバ変数の存在が必要です。 yii\console\controllers\FixtureController
prompt() ユーザーに入力を促し、それを検証します。 yii\console\Controller
render() ビューをレンダリングし、レイアウトが利用可能な場合は適用します。 yii\base\Controller
renderContent() レイアウトを適用して静的な文字列をレンダリングします。 yii\base\Controller
renderFile() ビューファイルをレンダリングします。 yii\base\Controller
renderPartial() レイアウトを適用せずにビューをレンダリングします。 yii\base\Controller
run() ルートで指定されたリクエストを実行します。 yii\base\Controller
runAction() 指定されたアクションIDとパラメータを使用してアクションを実行します。 yii\console\Controller
select() ユーザーに選択オプションを提供します。「?」を入力すると、選択可能なオプションとその説明のリストが表示されます。 yii\console\Controller
setView() このコントローラで使用されるビューオブジェクトを設定します。 yii\base\Controller
setViewPath() ビューファイルを含むディレクトリを設定します。 yii\base\Controller
stderr() STDERRに文字列を出力します。 yii\console\Controller
stdout() STDOUTに文字列を出力します。 yii\console\Controller
trigger() イベントをトリガーします。 yii\base\Component
unloadFixtures() 指定されたフィクスチャをアンロードします。 yii\test\FixtureTrait

保護されたメソッド

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

メソッド 説明 定義元
bindInjectedParams() アクションメソッドのシグネチャ内の型と名前に基づいてパラメータを設定します。 yii\base\Controller
createFixtures() 指定されたフィクスチャインスタンスを作成します。 yii\test\FixtureTrait
getActionMethodReflection() yii\console\Controller
parseDocCommentDetail() docblockから完全な説明を返します。 yii\console\Controller
parseDocCommentSummary() docblockの最初の行を返します。 yii\console\Controller
parseDocCommentTags() コメントブロックをタグに解析します。 yii\console\Controller

イベント

継承されたイベントを非表示

イベント 説明 定義元
EVENT_AFTER_ACTION yii\base\ActionEvent コントローラアクションの実行直後に発生するイベント。 yii\base\Controller
EVENT_BEFORE_ACTION yii\base\ActionEvent コントローラアクションの実行直前に発生するイベント。 yii\base\Controller

定数

継承された定数を非表示

定数 説明 定義元
EXIT_CODE_ERROR 1 2.0.13以降非推奨。代わりにyii\console\ExitCode::UNSPECIFIED_ERRORを使用してください。 yii\console\Controller
EXIT_CODE_NORMAL 0 2.0.13以降非推奨。代わりにyii\console\ExitCode::OKを使用してください。 yii\console\Controller

プロパティの詳細

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

$defaultAction public property

コントローラのデフォルトアクションID。

public string $defaultAction 'load'
$globalFixtures public property

ロードおよびアンロード時に適用する必要があるグローバルフィクスチャ。デフォルトでは、整合性チェックを無効化および有効化する`InitDbFixture`に設定されているため、データを安全にロードできます。

public array $globalFixtures = [
    
'yii\test\InitDbFixture',
]
$namespace public property

フィクスチャを検索するデフォルトの名前空間。

public string $namespace 'tests\unit\fixtures'

メソッドの詳細

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

__call() public method

定義先: yii\base\Component::__call()

クラスメソッドではない名前付きメソッドを呼び出します。

このメソッドは、アタッチされているビヘイビアに名前付きメソッドがあるかどうかをチェックし、利用可能な場合は実行します。

これはPHPのマジックメソッドであり、未知のメソッドが呼び出されたときに暗黙的に呼び出されるため、直接呼び出さないでください。

public mixed __call ( $name, $params )
$name string

メソッド名

$params array

メソッドパラメータ

戻り値 mixed

メソッドの戻り値

例外 yii\base\UnknownMethodException

未知のメソッドを呼び出した場合

                public function __call($name, $params)
{
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $object) {
        if ($object->hasMethod($name)) {
            return call_user_func_array([$object, $name], $params);
        }
    }
    throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}

            
__clone() public method

定義先: yii\base\Component::__clone()

このメソッドは、既存のオブジェクトをクローンしてオブジェクトが作成された後に呼び出されます。

ビヘイビアは古いオブジェクトにアタッチされているため、すべてのビヘイビアを削除します。

public void __clone ( )

                public function __clone()
{
    $this->_events = [];
    $this->_eventWildcards = [];
    $this->_behaviors = null;
}

            
__construct() public method
public void __construct ( $id, $module, $config = [] )
$id string

このコントローラのID。

$module yii\base\Module

このコントローラが属するモジュール。

$config array

オブジェクトのプロパティを初期化するために使用される名前と値のペア。

                public function __construct($id, $module, $config = [])
{
    $this->id = $id;
    $this->module = $module;
    parent::__construct($config);
}

            
__get() publicメソッド

定義されている場所: yii\base\Component::__get()

コンポーネントプロパティの値を返します。

このメソッドは、以下の順番でチェックし、それに応じて動作します。

  • ゲッターによって定義されたプロパティ: ゲッターの結果を返します。
  • ビヘイビアのプロパティ: ビヘイビアのプロパティ値を返します。

これはPHPのマジックメソッドであり、`$value = $component->property;`を実行した際に暗黙的に呼び出されるため、直接呼び出さないでください。

こちらも参照してください __set()

public mixed __get ( $name )
$name string

プロパティ名

戻り値 mixed

プロパティ値、またはビヘイビアのプロパティの値

例外 yii\base\UnknownPropertyException

プロパティが定義されていない場合

例外 yii\base\InvalidCallException

プロパティが書き込み専用の場合。

                public function __get($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        // read property, e.g. getName()
        return $this->$getter();
    }
    // behavior property
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canGetProperty($name)) {
            return $behavior->$name;
        }
    }
    if (method_exists($this, 'set' . $name)) {
        throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
    }
    throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}

            
__isset() publicメソッド

定義されている場所: yii\base\Component::__isset()

プロパティが設定されているかどうか(つまり、定義されていてnullではないかどうか)を確認します。

このメソッドは、以下の順番でチェックし、それに応じて動作します。

  • セッターによって定義されたプロパティ: プロパティが設定されているかどうかを返します。
  • ビヘイビアのプロパティ: プロパティが設定されているかどうかを返します。
  • 存在しないプロパティの場合は`false`を返します。

これはPHPのマジックメソッドであり、`isset($component->property)`を実行した際に暗黙的に呼び出されるため、直接呼び出さないでください。

こちらも参照してください https://www.php.net/manual/en/function.isset.php

public boolean __isset ( $name )
$name string

プロパティ名またはイベント名

戻り値 boolean

指定されたプロパティが設定されているかどうか

                public function __isset($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        return $this->$getter() !== null;
    }
    // behavior property
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canGetProperty($name)) {
            return $behavior->$name !== null;
        }
    }
    return false;
}

            
__set() publicメソッド

定義されている場所: yii\base\Component::__set()

コンポーネントプロパティの値を設定します。

このメソッドは、以下の順番でチェックし、それに応じて動作します。

  • セッターによって定義されたプロパティ: プロパティ値を設定します。
  • "on xyz"形式のイベント: "xyz"イベントにハンドラーをアタッチします。
  • "as xyz"形式のビヘイビア: "xyz"という名前のビヘイビアをアタッチします。
  • ビヘイビアのプロパティ: ビヘイビアのプロパティ値を設定します。

これはPHPのマジックメソッドであり、`$component->property = $value;`を実行した際に暗黙的に呼び出されるため、直接呼び出さないでください。

こちらも参照してください __get()

public void __set ( $name, $value )
$name string

プロパティ名またはイベント名

$value mixed

プロパティ値

例外 yii\base\UnknownPropertyException

プロパティが定義されていない場合

例外 yii\base\InvalidCallException

プロパティが読み取り専用の場合。

                public function __set($name, $value)
{
    $setter = 'set' . $name;
    if (method_exists($this, $setter)) {
        // set property
        $this->$setter($value);
        return;
    } elseif (strncmp($name, 'on ', 3) === 0) {
        // on event: attach event handler
        $this->on(trim(substr($name, 3)), $value);
        return;
    } elseif (strncmp($name, 'as ', 3) === 0) {
        // as behavior: attach behavior
        $name = trim(substr($name, 3));
        $this->attachBehavior($name, $value instanceof Behavior ? $value : Yii::createObject($value));
        return;
    }
    // behavior property
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canSetProperty($name)) {
            $behavior->$name = $value;
            return;
        }
    }
    if (method_exists($this, 'get' . $name)) {
        throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
    }
    throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
}

            
__unset() publicメソッド

定義されている場所: yii\base\Component::__unset()

コンポーネントプロパティをnullに設定します。

このメソッドは、以下の順番でチェックし、それに応じて動作します。

  • セッターによって定義されたプロパティ: プロパティ値をnullに設定します。
  • ビヘイビアのプロパティ: プロパティ値をnullに設定します。

これはPHPのマジックメソッドであり、`unset($component->property)`を実行した際に暗黙的に呼び出されるため、直接呼び出さないでください。

こちらも参照してください https://www.php.net/manual/en/function.unset.php

public void __unset ( $name )
$name string

プロパティ名

例外 yii\base\InvalidCallException

プロパティが読み取り専用の場合。

                public function __unset($name)
{
    $setter = 'set' . $name;
    if (method_exists($this, $setter)) {
        $this->$setter(null);
        return;
    }
    // behavior property
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canSetProperty($name)) {
            $behavior->$name = null;
            return;
        }
    }
    throw new InvalidCallException('Unsetting an unknown or read-only property: ' . get_class($this) . '::' . $name);
}

            
actionLoad() publicメソッド

指定されたフィクスチャデータを読み込みます。

例えば、

# load the fixture data specified by User and UserProfile.
# any existing fixture data will be removed first
yii fixture/load "User, UserProfile"

# load all available fixtures found under 'tests\unit\fixtures'
yii fixture/load "*"

# load all fixtures except User and UserProfile
yii fixture/load "*, -User, -UserProfile"
public integer actionLoad ( array $fixturesInput = [] )
$fixturesInput array
戻り値 integer

リターンコード

例外 yii\console\Exception

指定されたフィクスチャが存在しない場合。

                public function actionLoad(array $fixturesInput = [])
{
    if ($fixturesInput === []) {
        $this->printHelpMessage();
        return ExitCode::OK;
    }
    $filtered = $this->filterFixtures($fixturesInput);
    $except = $filtered['except'];
    if (!$this->needToApplyAll($fixturesInput[0])) {
        $fixtures = $filtered['apply'];
        $foundFixtures = $this->findFixtures($fixtures);
        $notFoundFixtures = array_diff($fixtures, $foundFixtures);
        if ($notFoundFixtures !== []) {
            $this->notifyNotFound($notFoundFixtures);
        }
    } else {
        $foundFixtures = $this->findFixtures();
    }
    $fixturesToLoad = array_diff($foundFixtures, $except);
    if (!$foundFixtures) {
        throw new Exception(
            'No files were found for: "' . implode(', ', $fixturesInput) . "\".\n" .
            "Check that files exist under fixtures path: \n\"" . $this->getFixturePath() . '".'
        );
    }
    if ($fixturesToLoad === []) {
        $this->notifyNothingToLoad($foundFixtures, $except);
        return ExitCode::OK;
    }
    if (!$this->confirmLoad($fixturesToLoad, $except)) {
        return ExitCode::OK;
    }
    $fixtures = $this->getFixturesConfig(array_merge($this->globalFixtures, $fixturesToLoad));
    if (!$fixtures) {
        throw new Exception('No fixtures were found in namespace: "' . $this->namespace . '"' . '');
    }
    $fixturesObjects = $this->createFixtures($fixtures);
    $this->unloadFixtures($fixturesObjects);
    $this->loadFixtures($fixturesObjects);
    $this->notifyLoaded($fixturesObjects);
    return ExitCode::OK;
}

            
actionUnload() publicメソッド

指定されたフィクスチャをアンロードします。

例えば、

# unload the fixture data specified by User and UserProfile.
yii fixture/unload "User, UserProfile"

# unload all fixtures found under 'tests\unit\fixtures'
yii fixture/unload "*"

# unload all fixtures except User and UserProfile
yii fixture/unload "*, -User, -UserProfile"
public integer actionUnload ( array $fixturesInput = [] )
$fixturesInput array
戻り値 integer

リターンコード

例外 yii\console\Exception

指定されたフィクスチャが存在しない場合。

                public function actionUnload(array $fixturesInput = [])
{
    if ($fixturesInput === []) {
        $this->printHelpMessage();
        return ExitCode::OK;
    }
    $filtered = $this->filterFixtures($fixturesInput);
    $except = $filtered['except'];
    if (!$this->needToApplyAll($fixturesInput[0])) {
        $fixtures = $filtered['apply'];
        $foundFixtures = $this->findFixtures($fixtures);
        $notFoundFixtures = array_diff($fixtures, $foundFixtures);
        if ($notFoundFixtures !== []) {
            $this->notifyNotFound($notFoundFixtures);
        }
    } else {
        $foundFixtures = $this->findFixtures();
    }
    if ($foundFixtures === []) {
        throw new Exception(
            'No files were found for: "' . implode(', ', $fixturesInput) . "\".\n" .
            "Check that files exist under fixtures path: \n\"" . $this->getFixturePath() . '".'
        );
    }
    $fixturesToUnload = array_diff($foundFixtures, $except);
    if ($fixturesToUnload === []) {
        $this->notifyNothingToUnload($foundFixtures, $except);
        return ExitCode::OK;
    }
    if (!$this->confirmUnload($fixturesToUnload, $except)) {
        return ExitCode::OK;
    }
    $fixtures = $this->getFixturesConfig(array_merge($this->globalFixtures, $fixturesToUnload));
    if ($fixtures === []) {
        throw new Exception('No fixtures were found in namespace: ' . $this->namespace . '".');
    }
    $this->unloadFixtures($this->createFixtures($fixtures));
    $this->notifyUnloaded($fixtures);
}

            
actions() publicメソッド

定義されている場所: yii\base\Controller::actions()

コントローラに対して外部アクションを宣言します。

このメソッドは、コントローラーの外部アクションを宣言するためにオーバーライドすることを意図しています。アクションIDをキー、対応するアクションクラス名またはアクション設定配列を値とする配列を返す必要があります。例えば、

return [
    'action1' => 'app\components\Action1',
    'action2' => [
        'class' => 'app\components\Action2',
        'property1' => 'value1',
        'property2' => 'value2',
    ],
];

Yii::createObject() は後で、ここで提供された設定を使用して要求されたアクションを作成するために使用されます。

public array actions ( )

                public function actions()
{
    return [];
}

            
afterAction() publicメソッド

定義されている場所: yii\base\Controller::afterAction()

このメソッドは、アクションが実行された直後に呼び出されます。

このメソッドは、EVENT_AFTER_ACTION イベントをトリガーします。メソッドの戻り値は、アクションの戻り値として使用されます。

このメソッドをオーバーライドする場合は、コードを次のように記述する必要があります。

public function afterAction($action, $result)
{
    $result = parent::afterAction($action, $result);
    // your custom code here
    return $result;
}
public mixed afterAction ( $action, $result )
$action yii\base\Action

実行されたばかりのアクション。

$result mixed

アクションの戻り値。

戻り値 mixed

処理済みのアクション結果。

                public function afterAction($action, $result)
{
    $event = new ActionEvent($action);
    $event->result = $result;
    $this->trigger(self::EVENT_AFTER_ACTION, $event);
    return $event->result;
}

            
ansiFormat() publicメソッド

定義されている場所: yii\console\Controller::ansiFormat()

ANSIコードで文字列をフォーマットします。

yii\helpers\Consoleで定義されている定数を使用して、追加のパラメーターを渡すことができます。

echo $this->ansiFormat('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE);
public string ansiFormat ( $string )
$string string

フォーマットする文字列

                public function ansiFormat($string)
{
    if ($this->isColorEnabled()) {
        $args = func_get_args();
        array_shift($args);
        $string = Console::ansiFormat($string, $args);
    }
    return $string;
}

            
attachBehavior() publicメソッド

定義されている場所: yii\base\Component::attachBehavior()

このコンポーネントにビヘイビアをアタッチします。

このメソッドは、指定された設定に基づいてビヘイビアオブジェクトを作成します。その後、yii\base\Behavior::attach()メソッドを呼び出すことで、ビヘイビアオブジェクトがこのコンポーネントにアタッチされます。

こちらも参照してください detachBehavior()

public yii\base\Behavior attachBehavior ( $name, $behavior )
$name string

ビヘイビアの名前。

$behavior string|array|yii\base\Behavior

動作設定。以下のいずれかになります。

  • yii\base\Behavior オブジェクト
  • ビヘイビアークラスを指定する文字列
  • ビヘイビアオブジェクトを作成するためにYii::createObject() に渡されるオブジェクト設定配列。
戻り値 yii\base\Behavior

ビヘイビアオブジェクト

                public function attachBehavior($name, $behavior)
{
    $this->ensureBehaviors();
    return $this->attachBehaviorInternal($name, $behavior);
}

            
attachBehaviors() publicメソッド

定義位置: yii\base\Component::attachBehaviors()

コンポーネントにビヘイビアのリストをアタッチします。

各ビヘイビアは名前でインデックスされており、yii\base\Behavior オブジェクト、ビヘイビアークラスを指定する文字列、またはビヘイビアを作成するための設定配列のいずれかである必要があります。

こちらも参照してください attachBehavior()

public void attachBehaviors ( $behaviors )
$behaviors array

コンポーネントにアタッチされるビヘイビアのリスト

                public function attachBehaviors($behaviors)
{
    $this->ensureBehaviors();
    foreach ($behaviors as $name => $behavior) {
        $this->attachBehaviorInternal($name, $behavior);
    }
}

            
beforeAction() publicメソッド

定義位置: yii\console\Controller::beforeAction()

このメソッドは、アクションが実行される直前に呼び出されます。

このメソッドはEVENT_BEFORE_ACTION イベントをトリガーします。メソッドの戻り値によって、アクションが実行を継続するかどうかが決まります。

アクションを実行しない場合、必要な出力を提供するか、リクエストをリダイレクトすることで、`beforeAction` コード内でリクエストを処理する必要があります。そうでなければ、レスポンスは空になります。

このメソッドをオーバーライドする場合は、コードを次のように記述する必要があります。

public function beforeAction($action)
{
    // your custom code here, if you want the code to run before action filters,
    // which are triggered on the [[EVENT_BEFORE_ACTION]] event, e.g. PageCache or AccessControl

    if (!parent::beforeAction($action)) {
        return false;
    }

    // other custom code here

    return true; // or false to not run the action
}
public boolean beforeAction ( $action )
$action yii\base\Action

実行されるアクション。

戻り値 boolean

アクションが実行を継続するかどうか。

                public function beforeAction($action)
{
    $silentExit = $this->silentExitOnException !== null ? $this->silentExitOnException : YII_ENV_TEST;
    Yii::$app->errorHandler->silentExitOnException = $silentExit;
    return parent::beforeAction($action);
}

            
behaviors() publicメソッド

定義位置: yii\base\Component::behaviors()

このコンポーネントが動作するビヘイビアのリストを返します。

子クラスは、このメソッドをオーバーライドして、動作させたいビヘイビアを指定できます。

このメソッドの戻り値は、ビヘイビア名でインデックスされたビヘイビアオブジェクトまたは設定の配列である必要があります。ビヘイビアの設定は、ビヘイビアークラスを指定する文字列、または以下の構造の配列のいずれかです。

'behaviorName' => [
    'class' => 'BehaviorClass',
    'property1' => 'value1',
    'property2' => 'value2',
]

ビヘイビアクラスはyii\base\Behaviorを拡張する必要があることに注意してください。ビヘイビアは名前付きで、または匿名でアタッチできます。配列キーとして名前を使用する場合、この名前を使用して、後でgetBehavior()でビヘイビアを取得したり、detachBehavior()でデタッチしたりできます。匿名のビヘイビアは取得またはデタッチできません。

このメソッドで宣言されたビヘイビアは、コンポーネントに自動的に(オンデマンドで)アタッチされます。

public array behaviors ( )
戻り値 array

ビヘイビアの設定。

                public function behaviors()
{
    return [];
}

            
bindActionParams() publicメソッド

定義位置: yii\console\Controller::bindActionParams()

パラメータをアクションにバインドします。

このメソッドは、指定されたパラメータで実行を開始するときにyii\base\Actionによって呼び出されます。このメソッドは、まず、アクションで使用可能なoptionsを使用してパラメータをバインドします。次に、指定された引数を検証します。

public array bindActionParams ( $action, $params )
$action yii\base\Action

パラメータとバインドされるアクション

$params array

アクションにバインドされるパラメータ

戻り値 array

アクションが実行できる有効なパラメータ。

例外 yii\console\Exception

不明なオプションまたは不足している引数がある場合

                public function bindActionParams($action, $params)
{
    if ($action instanceof InlineAction) {
        $method = new \ReflectionMethod($this, $action->actionMethod);
    } else {
        $method = new \ReflectionMethod($action, 'run');
    }
    $args = [];
    $missing = [];
    $actionParams = [];
    $requestedParams = [];
    foreach ($method->getParameters() as $i => $param) {
        $name = $param->getName();
        $key = null;
        if (array_key_exists($i, $params)) {
            $key = $i;
        } elseif (array_key_exists($name, $params)) {
            $key = $name;
        }
        if ($key !== null) {
            if (PHP_VERSION_ID >= 80000) {
                $isArray = ($type = $param->getType()) instanceof \ReflectionNamedType && $type->getName() === 'array';
            } else {
                $isArray = $param->isArray();
            }
            if ($isArray) {
                $params[$key] = $params[$key] === '' ? [] : preg_split('/\s*,\s*/', $params[$key]);
            }
            $args[] = $actionParams[$key] = $params[$key];
            unset($params[$key]);
        } elseif (
            PHP_VERSION_ID >= 70100
            && ($type = $param->getType()) !== null
            && $type instanceof \ReflectionNamedType
            && !$type->isBuiltin()
        ) {
            try {
                $this->bindInjectedParams($type, $name, $args, $requestedParams);
            } catch (\yii\base\Exception $e) {
                throw new Exception($e->getMessage());
            }
        } elseif ($param->isDefaultValueAvailable()) {
            $args[] = $actionParams[$i] = $param->getDefaultValue();
        } else {
            $missing[] = $name;
        }
    }
    if (!empty($missing)) {
        throw new Exception(Yii::t('yii', 'Missing required arguments: {params}', ['params' => implode(', ', $missing)]));
    }
    // We use a different array here, specifically one that doesn't contain service instances but descriptions instead.
    if (\Yii::$app->requestedParams === null) {
        \Yii::$app->requestedParams = array_merge($actionParams, $requestedParams);
    }
    return array_merge($args, $params);
}

            
bindInjectedParams() protectedメソッド (バージョン2.0.36以降で使用可能)

定義位置: yii\base\Controller::bindInjectedParams()

アクションメソッドのシグネチャ内の型と名前に基づいてパラメータを設定します。

protected void bindInjectedParams ( ReflectionType $type, $name, &$args, &$requestedParams )
$type ReflectionType

アクションパラメータのリフレクション型。

$name string

パラメータの名前。

$args array

アクションの引数の配列。この関数は、それに項目を追加することがあります。

$requestedParams array

要求されたパラメータを含む配列。この関数は、特定のキーを書き込むことがあります。

例外 yii\base\ErrorException

必要なサービスを読み込めなかった場合。

例外 yii\base\InvalidConfigException

DI設定にエラーがある場合にスローされます。

例外 yii\di\NotInstantiableException

定義をコンテナに適切な定義がない状態で具体的なクラス(インターフェース型ヒントなど)に解決できない場合にスローされます。

                final protected function bindInjectedParams(\ReflectionType $type, $name, &$args, &$requestedParams)
{
    // Since it is not a builtin type it must be DI injection.
    $typeName = $type->getName();
    if (($component = $this->module->get($name, false)) instanceof $typeName) {
        $args[] = $component;
        $requestedParams[$name] = 'Component: ' . get_class($component) . " \$$name";
    } elseif ($this->module->has($typeName) && ($service = $this->module->get($typeName)) instanceof $typeName) {
        $args[] = $service;
        $requestedParams[$name] = 'Module ' . get_class($this->module) . " DI: $typeName \$$name";
    } elseif (\Yii::$container->has($typeName) && ($service = \Yii::$container->get($typeName)) instanceof $typeName) {
        $args[] = $service;
        $requestedParams[$name] = "Container DI: $typeName \$$name";
    } elseif ($type->allowsNull()) {
        $args[] = null;
        $requestedParams[$name] = "Unavailable service: $name";
    } else {
        throw new Exception('Could not load required service: ' . $name);
    }
}

            
canGetProperty() publicメソッド

定義位置: yii\base\Component::canGetProperty()

プロパティを読み取ることができるかどうかを示す値を返します。

プロパティは、以下の場合に読み取ることができます。

  • クラスに指定された名前に関連付けられたゲッターメソッドがある場合(この場合、プロパティ名は大文字と小文字が区別されません)。
  • クラスに指定された名前のメンバ変数がある場合(`$checkVars` がtrueの場合)。
  • アタッチされたビヘイビアに、指定された名前の読み取り可能なプロパティがある場合(`$checkBehaviors` がtrueの場合)。

こちらも参照してください canSetProperty()

public boolean canGetProperty ( $name, $checkVars true, $checkBehaviors true )
$name string

プロパティ名

$checkVars boolean

メンバ変数をプロパティとして扱うかどうか

$checkBehaviors boolean

ビヘイビアのプロパティをこのコンポーネントのプロパティとして扱うかどうか

戻り値 boolean

プロパティを読み取ることができるかどうか

                public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
{
    if (method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name)) {
        return true;
    } elseif ($checkBehaviors) {
        $this->ensureBehaviors();
        foreach ($this->_behaviors as $behavior) {
            if ($behavior->canGetProperty($name, $checkVars)) {
                return true;
            }
        }
    }
    return false;
}

            
canSetProperty() publicメソッド

定義位置: yii\base\Component::canSetProperty()

プロパティを設定できるかどうかを示す値を返します。

プロパティは、以下の場合に書き込むことができます。

  • クラスに指定された名前に関連付けられたセッターメソッドがある場合(この場合、プロパティ名は大文字と小文字が区別されません)。
  • クラスに指定された名前のメンバ変数がある場合(`$checkVars` がtrueの場合)。
  • アタッチされたビヘイビアに、指定された名前の書き込み可能なプロパティがある場合(`$checkBehaviors` がtrueの場合)。

こちらも参照してください canGetProperty()

public boolean canSetProperty ( $name, $checkVars true, $checkBehaviors true )
$name string

プロパティ名

$checkVars boolean

メンバ変数をプロパティとして扱うかどうか

$checkBehaviors boolean

ビヘイビアのプロパティをこのコンポーネントのプロパティとして扱うかどうか

戻り値 boolean

プロパティを書き込むことができるかどうか

                public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
{
    if (method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name)) {
        return true;
    } elseif ($checkBehaviors) {
        $this->ensureBehaviors();
        foreach ($this->_behaviors as $behavior) {
            if ($behavior->canSetProperty($name, $checkVars)) {
                return true;
            }
        }
    }
    return false;
}

            
className() public static メソッド
2.0.14 より非推奨。PHP >= 5.5 では、代わりに ::class を使用してください。

定義位置: yii\base\BaseObject::className()

このクラスの完全修飾名を返します。

public static string className ( )
戻り値 string

このクラスの完全修飾名。

                public static function className()
{
    return get_called_class();
}

            
confirm() public メソッド

定義位置: yii\console\Controller::confirm()

yまたはnを入力してユーザーに確認を求めます。

一般的な使用例は以下のとおりです。

if ($this->confirm("Are you sure?")) {
    echo "user typed yes\n";
} else {
    echo "user typed no\n";
}
public boolean confirm ( $message, $default false )
$message string

ユーザー入力待ちの前に出力されます。

$default boolean

選択が行われなかった場合に返される値。

戻り値 boolean

ユーザーが確認したかどうか。 $interactive が false の場合、true を返します。

                public function confirm($message, $default = false)
{
    if ($this->interactive) {
        return Console::confirm($message, $default);
    }
    return true;
}

            
createAction() public メソッド

定義位置: yii\base\Controller::createAction()

指定されたアクションIDに基づいてアクションを作成します。

このメソッドは、まず、アクション ID が actions() で宣言されているかどうかをチェックします。宣言されている場合は、そこで宣言された設定を使用してアクションオブジェクトを作成します。宣言されていない場合は、アクション ID が xyz である actionXyz の形式の controller メソッドを探します。見つかった場合は、そのメソッドを表す yii\base\InlineAction が作成され、返されます。

public yii\base\Action|null createAction ( $id )
$id string

アクション ID。

戻り値 yii\base\Action|null

新しく作成されたアクションインスタンス。ID がアクションに解決されない場合は null。

                public function createAction($id)
{
    if ($id === '') {
        $id = $this->defaultAction;
    }
    $actionMap = $this->actions();
    if (isset($actionMap[$id])) {
        return Yii::createObject($actionMap[$id], [$id, $this]);
    }
    if (preg_match('/^(?:[a-z0-9_]+-)*[a-z0-9_]+$/', $id)) {
        $methodName = 'action' . str_replace(' ', '', ucwords(str_replace('-', ' ', $id)));
        if (method_exists($this, $methodName)) {
            $method = new \ReflectionMethod($this, $methodName);
            if ($method->isPublic() && $method->getName() === $methodName) {
                return new InlineAction($id, $this, $methodName);
            }
        }
    }
    return null;
}

            
createFixtures() protected メソッド

定義位置: yii\test\FixtureTrait::createFixtures()

指定されたフィクスチャインスタンスを作成します。

すべての依存関係のあるフィクスチャも作成されます。重複するフィクスチャと循環依存関係は、一度だけ作成されます。

protected yii\test\Fixture[] createFixtures ( array $fixtures )
$fixtures array

作成するフィクスチャ。フィクスチャ名またはフィクスチャ設定を提供できます。このパラメータが提供されない場合、 globalFixtures()fixtures() で指定されたフィクスチャが作成されます。

戻り値 yii\test\Fixture[]

作成されたフィクスチャインスタンス

例外 yii\base\InvalidConfigException

フィクスチャが正しく設定されていない場合

                protected function createFixtures(array $fixtures)
{
    // normalize fixture configurations
    $config = [];  // configuration provided in test case
    $aliases = [];  // class name => alias or class name
    foreach ($fixtures as $name => $fixture) {
        if (!is_array($fixture)) {
            $class = ltrim($fixture, '\\');
            $fixtures[$name] = ['class' => $class];
            $aliases[$class] = is_int($name) ? $class : $name;
        } elseif (isset($fixture['class'])) {
            $class = ltrim($fixture['class'], '\\');
            $config[$class] = $fixture;
            $aliases[$class] = $name;
        } else {
            throw new InvalidConfigException("You must specify 'class' for the fixture '$name'.");
        }
    }
    // create fixture instances
    $instances = [];
    $stack = array_reverse($fixtures);
    while (($fixture = array_pop($stack)) !== null) {
        if ($fixture instanceof Fixture) {
            $class = get_class($fixture);
            $name = isset($aliases[$class]) ? $aliases[$class] : $class;
            unset($instances[$name]);  // unset so that the fixture is added to the last in the next line
            $instances[$name] = $fixture;
        } else {
            $class = ltrim($fixture['class'], '\\');
            $name = isset($aliases[$class]) ? $aliases[$class] : $class;
            if (!isset($instances[$name])) {
                $instances[$name] = false;
                $stack[] = $fixture = Yii::createObject($fixture);
                foreach ($fixture->depends as $dep) {
                    // need to use the configuration provided in test case
                    $stack[] = isset($config[$dep]) ? $config[$dep] : ['class' => $dep];
                }
            }
            // if the fixture is already loaded (ie. a circular dependency or if two fixtures depend on the same fixture) just skip it.
        }
    }
    return $instances;
}

            
detachBehavior() public メソッド

定義位置: yii\base\Component::detachBehavior()

コンポーネントからビヘイビアをデタッチします。

ビヘイビアの yii\base\Behavior::detach() メソッドが呼び出されます。

public yii\base\Behavior|null detachBehavior ( $name )
$name string

ビヘイビアの名前。

戻り値 yii\base\Behavior|null

デタッチされたビヘイビア。ビヘイビアが存在しない場合は null。

                public function detachBehavior($name)
{
    $this->ensureBehaviors();
    if (isset($this->_behaviors[$name])) {
        $behavior = $this->_behaviors[$name];
        unset($this->_behaviors[$name]);
        $behavior->detach();
        return $behavior;
    }
    return null;
}

            
detachBehaviors() public メソッド

定義位置: yii\base\Component::detachBehaviors()

コンポーネントからすべてのビヘイビアをデタッチします。

public void detachBehaviors ( )

                public function detachBehaviors()
{
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $name => $behavior) {
        $this->detachBehavior($name);
    }
}

            
ensureBehaviors() public メソッド

定義位置: yii\base\Component::ensureBehaviors()

behaviors()で宣言されたビヘイビアがこのコンポーネントにアタッチされていることを確認します。

public void ensureBehaviors ( )

                public function ensureBehaviors()
{
    if ($this->_behaviors === null) {
        $this->_behaviors = [];
        foreach ($this->behaviors() as $name => $behavior) {
            $this->attachBehaviorInternal($name, $behavior);
        }
    }
}

            
findLayoutFile() public メソッド

定義位置: yii\base\Controller::findLayoutFile()

適用可能なレイアウトファイルを見つけます。

public string|boolean findLayoutFile ( $view )
$view yii\base\View

レイアウトファイルを表示するビューオブジェクト。

戻り値 string|boolean

レイアウトファイルパス、またはレイアウトが不要な場合は false。このパラメータの指定方法については、 render() を参照してください。

例外 yii\base\InvalidArgumentException

無効なパスエイリアスを使用してレイアウトを指定した場合。

                public function findLayoutFile($view)
{
    $module = $this->module;
    $layout = null;
    if (is_string($this->layout)) {
        $layout = $this->layout;
    } elseif ($this->layout === null) {
        while ($module !== null && $module->layout === null) {
            $module = $module->module;
        }
        if ($module !== null && is_string($module->layout)) {
            $layout = $module->layout;
        }
    }
    if ($layout === null) {
        return false;
    }
    if (strncmp($layout, '@', 1) === 0) {
        $file = Yii::getAlias($layout);
    } elseif (strncmp($layout, '/', 1) === 0) {
        $file = Yii::$app->getLayoutPath() . DIRECTORY_SEPARATOR . substr($layout, 1);
    } else {
        $file = $module->getLayoutPath() . DIRECTORY_SEPARATOR . $layout;
    }
    if (pathinfo($file, PATHINFO_EXTENSION) !== '') {
        return $file;
    }
    $path = $file . '.' . $view->defaultExtension;
    if ($view->defaultExtension !== 'php' && !is_file($path)) {
        $path = $file . '.php';
    }
    return $path;
}

            
fixtures() public メソッド

定義位置: yii\test\FixtureTrait::fixtures()

現在のテストケースに必要なフィクスチャを宣言します。

このメソッドの戻り値は、フィクスチャ設定の配列でなければなりません。例えば、

[
    // anonymous fixture
    PostFixture::class,
    // "users" fixture
    'users' => UserFixture::class,
    // "cache" fixture with configuration
    'cache' => [
         'class' => CacheFixture::class,
         'host' => 'xxx',
    ],
]

テストケースで使用される実際のフィクスチャには、 globalFixtures()fixtures() の両方が含まれることに注意してください。

public array fixtures ( )
戻り値 array

現在のテストケースに必要なフィクスチャ

                public function fixtures()
{
    return [];
}

            
getActionArgsHelp() public メソッド

定義位置: yii\console\Controller::getActionArgsHelp()

アクションの匿名引数に関するヘルプ情報を返します。

戻り値は配列である必要があります。キーは引数名で、値は対応するヘルプ情報です。各値は、以下の構造の配列でなければなりません。

  • required: bool, この引数が必須かどうか
  • type: string|null, この引数のPHPの型
  • default: mixed, この引数のデフォルト値
  • comment: string, この引数の説明

デフォルトの実装では、アクションメソッドに対応するパラメーターのReflectionまたはDocBlockから抽出されたヘルプ情報を返します。

public array getActionArgsHelp ( $action )
$action yii\base\Action

アクションインスタンス

戻り値 array

アクション引数のヘルプ情報

                public function getActionArgsHelp($action)
{
    $method = $this->getActionMethodReflection($action);
    $tags = $this->parseDocCommentTags($method);
    $tags['param'] = isset($tags['param']) ? (array) $tags['param'] : [];
    $phpDocParams = [];
    foreach ($tags['param'] as $i => $tag) {
        if (preg_match('/^(?<type>\S+)(\s+\$(?<name>\w+))?(?<comment>.*)/us', $tag, $matches) === 1) {
            $key = empty($matches['name']) ? $i : $matches['name'];
            $phpDocParams[$key] = ['type' => $matches['type'], 'comment' => $matches['comment']];
        }
    }
    unset($tags);
    $args = [];
    /** @var \ReflectionParameter $parameter */
    foreach ($method->getParameters() as $i => $parameter) {
        $type = null;
        $comment = '';
        if (PHP_MAJOR_VERSION > 5 && $parameter->hasType()) {
            $reflectionType = $parameter->getType();
            if (PHP_VERSION_ID >= 70100) {
                $types = method_exists($reflectionType, 'getTypes') ? $reflectionType->getTypes() : [$reflectionType];
                foreach ($types as $key => $reflectionType) {
                    $types[$key] = $reflectionType->getName();
                }
                $type = implode('|', $types);
            } else {
                $type = (string) $reflectionType;
            }
        }
        // find PhpDoc tag by property name or position
        $key = isset($phpDocParams[$parameter->name]) ? $parameter->name : (isset($phpDocParams[$i]) ? $i : null);
        if ($key !== null) {
            $comment = $phpDocParams[$key]['comment'];
            if ($type === null && !empty($phpDocParams[$key]['type'])) {
                $type = $phpDocParams[$key]['type'];
            }
        }
        // if type still not detected, then using type of default value
        if ($type === null && $parameter->isDefaultValueAvailable() && $parameter->getDefaultValue() !== null) {
            $type = gettype($parameter->getDefaultValue());
        }
        $args[$parameter->name] = [
            'required' => !$parameter->isOptional(),
            'type' => $type,
            'default' => $parameter->isDefaultValueAvailable() ? $parameter->getDefaultValue() : null,
            'comment' => $comment,
        ];
    }
    return $args;
}

            
getActionHelp() public メソッド

定義位置: yii\console\Controller::getActionHelp()

指定されたアクションの詳細なヘルプ情報を返します。

public string getActionHelp ( $action )
$action yii\base\Action

ヘルプを取得するアクション

戻り値 string

指定されたアクションの詳細なヘルプ情報。

                public function getActionHelp($action)
{
    return $this->parseDocCommentDetail($this->getActionMethodReflection($action));
}

            
getActionHelpSummary() public メソッド

定義位置: yii\console\Controller::getActionHelpSummary()

指定されたアクションを記述する1行の短い概要を返します。

public string getActionHelpSummary ( $action )
$action yii\base\Action

概要を取得するアクション

戻り値 string

指定されたアクションを説明する1行の短い概要。

                public function getActionHelpSummary($action)
{
    if ($action === null) {
        return $this->ansiFormat(Yii::t('yii', 'Action not found.'), Console::FG_RED);
    }
    return $this->parseDocCommentSummary($this->getActionMethodReflection($action));
}

            
getActionMethodReflection() protected メソッド
protected ReflectionFunctionAbstract getActionMethodReflection ( $action )
$action yii\base\Action

                protected function getActionMethodReflection($action)
{
    if (!isset($this->_reflections[$action->id])) {
        if ($action instanceof InlineAction) {
            $this->_reflections[$action->id] = new \ReflectionMethod($this, $action->actionMethod);
        } else {
            $this->_reflections[$action->id] = new \ReflectionMethod($action, 'run');
        }
    }
    return $this->_reflections[$action->id];
}

            
getActionOptionsHelp() public メソッド

定義位置: yii\console\Controller::getActionOptionsHelp()

アクションのオプションに関するヘルプ情報を返します。

返される値は配列である必要があります。キーはオプション名で、値は対応するヘルプ情報です。各値は以下の構造の配列でなければなりません。

  • type: string, この引数のPHPの型。
  • default: string, この引数のデフォルト値。
  • comment: string, この引数のコメント。

デフォルトの実装では、アクションオプションに対応するプロパティのdoc-commentから抽出したヘルプ情報を返します。

public array getActionOptionsHelp ( $action )
$action yii\base\Action
戻り値 array

アクションオプションのヘルプ情報

                public function getActionOptionsHelp($action)
{
    $optionNames = $this->options($action->id);
    if (empty($optionNames)) {
        return [];
    }
    $class = new \ReflectionClass($this);
    $options = [];
    foreach ($class->getProperties() as $property) {
        $name = $property->getName();
        if (!in_array($name, $optionNames, true)) {
            continue;
        }
        $defaultValue = $property->getValue($this);
        $tags = $this->parseDocCommentTags($property);
        // Display camelCase options in kebab-case
        $name = Inflector::camel2id($name, '-', true);
        if (isset($tags['var']) || isset($tags['property'])) {
            $doc = isset($tags['var']) ? $tags['var'] : $tags['property'];
            if (is_array($doc)) {
                $doc = reset($doc);
            }
            if (preg_match('/^(\S+)(.*)/s', $doc, $matches)) {
                $type = $matches[1];
                $comment = $matches[2];
            } else {
                $type = null;
                $comment = $doc;
            }
            $options[$name] = [
                'type' => $type,
                'default' => $defaultValue,
                'comment' => $comment,
            ];
        } else {
            $options[$name] = [
                'type' => null,
                'default' => $defaultValue,
                'comment' => '',
            ];
        }
    }
    return $options;
}

            
getBehavior() public メソッド

定義位置: yii\base\Component::getBehavior()

名前付きのビヘイビアオブジェクトを返します。

public yii\base\Behavior|null getBehavior ( $name )
$name string

ビヘイビア名

戻り値 yii\base\Behavior|null

ビヘイビアオブジェクト、またはビヘイビアが存在しない場合はnull。

                public function getBehavior($name)
{
    $this->ensureBehaviors();
    return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
}

            
getBehaviors() public メソッド

定義位置: yii\base\Component::getBehaviors()

このコンポーネントにアタッチされているすべてのビヘイビアを返します。

public yii\base\Behavior[] getBehaviors ( )
戻り値 yii\base\Behavior[]

このコンポーネントにアタッチされたビヘイビアのリスト。

                public function getBehaviors()
{
    $this->ensureBehaviors();
    return $this->_behaviors;
}

            
getFixture() public メソッド

定義位置: yii\test\FixtureTrait::getFixture()

名前付きのフィクスチャを返します。

public yii\test\Fixture|null getFixture ( $name )
$name string

フィクスチャ名。これは、フィクスチャのエイリアス名、またはエイリアスが使用されていない場合はクラス名です。

戻り値 yii\test\Fixture|null

フィクスチャオブジェクト、または指定されたフィクスチャが存在しない場合はnull。

                public function getFixture($name)
{
    if ($this->_fixtures === null) {
        $this->_fixtures = $this->createFixtures(array_merge($this->globalFixtures(), $this->fixtures()));
    }
    $name = ltrim($name, '\\');
    return isset($this->_fixtures[$name]) ? $this->_fixtures[$name] : null;
}

            
getFixtures() public メソッド

定義位置: yii\test\FixtureTrait::getFixtures()

globalFixtures()fixtures() で指定されたフィクスチャオブジェクトを返します。

public yii\test\Fixture[] getFixtures ( )
戻り値 yii\test\Fixture[]

現在のテストケースのロード済みのフィクスチャ。

                public function getFixtures()
{
    if ($this->_fixtures === null) {
        $this->_fixtures = $this->createFixtures(array_merge($this->globalFixtures(), $this->fixtures()));
    }
    return $this->_fixtures;
}

            
getHelp() public メソッド

定義位置: yii\console\Controller::getHelp()

このコントローラのヘルプ情報を返します。

このメソッドをオーバーライドして、カスタマイズされたヘルプを返すことができます。デフォルトの実装では、PHPDocコメントから取得したヘルプ情報を返します。

public string getHelp ( )

                public function getHelp()
{
    return $this->parseDocCommentDetail(new \ReflectionClass($this));
}

            
getHelpSummary() public メソッド

定義位置: yii\console\Controller::getHelpSummary()

このコントローラを記述する1行の短い概要を返します。

このメソッドをオーバーライドして、カスタマイズされた概要を返すことができます。デフォルトの実装では、PHPDocコメントの最初の行を返します。

public string getHelpSummary ( )

                public function getHelpSummary()
{
    return $this->parseDocCommentSummary(new \ReflectionClass($this));
}

            
getModules() public メソッド

定義位置: yii\base\Controller::getModules()

このコントローラのすべての祖先モジュールを返します。

配列の最初のモジュールは最も外側のモジュール(つまり、アプリケーションインスタンス)で、最後のモジュールは最も内側のモジュールです。

public yii\base\Module[] getModules ( )
戻り値 yii\base\Module[]

このコントローラが配置されているすべての祖先モジュール。

                public function getModules()
{
    $modules = [$this->module];
    $module = $this->module;
    while ($module->module !== null) {
        array_unshift($modules, $module->module);
        $module = $module->module;
    }
    return $modules;
}

            
getOptionValues() public メソッド

定義位置: yii\console\Controller::getOptionValues()

アクションIDのオプションに対応するプロパティを返します。子クラスは、このメソッドをオーバーライドして可能なプロパティを指定できます。

public array getOptionValues ( $actionID )
$actionID string

現在のリクエストのアクションID。

戻り値 array

アクションのオプションに対応するプロパティ。

                public function getOptionValues($actionID)
{
    // $actionId might be used in subclasses to provide properties specific to action id
    $properties = [];
    foreach ($this->options($this->action->id) as $property) {
        $properties[$property] = $this->$property;
    }
    return $properties;
}

            
getPassedOptionValues() public メソッド

定義位置: yii\console\Controller::getPassedOptionValues()

渡されたオプションに対応するプロパティを返します。

public array getPassedOptionValues ( )
戻り値 array

渡されたオプションに対応するプロパティ。

                public function getPassedOptionValues()
{
    $properties = [];
    foreach ($this->_passedOptions as $property) {
        $properties[$property] = $this->$property;
    }
    return $properties;
}

            
getPassedOptions() public メソッド

定義位置: yii\console\Controller::getPassedOptions()

実行中に渡された有効なオプションの名前を返します。

public array getPassedOptions ( )
戻り値 array

実行中に渡されたオプションの名前。

                public function getPassedOptions()
{
    return $this->_passedOptions;
}

            
getRoute() publicメソッド

定義位置: yii\base\Controller::getRoute()

現在のリクエストのルートを返します。

public string getRoute ( )
戻り値 string

現在のリクエストのルート(モジュールID、コントローラID、アクションID)。

                public function getRoute()
{
    return $this->action !== null ? $this->action->getUniqueId() : $this->getUniqueId();
}

            
getUniqueId() publicメソッド

定義位置: yii\base\Controller::getUniqueId()

コントローラのユニークIDを返します。

public string getUniqueId ( )
戻り値 string

モジュールID(存在する場合)を接頭辞として付けたコントローラID。

                public function getUniqueId()
{
    return $this->module instanceof Application ? $this->id : $this->module->getUniqueId() . '/' . $this->id;
}

            
getView() publicメソッド

定義位置: yii\base\Controller::getView()

ビューまたはビューファイルをレンダリングするために使用できるビューオブジェクトを返します。

render()renderPartial()、およびrenderFile()メソッドは、このビューオブジェクトを使用して実際のビューレンダリングを実行します。設定されていない場合、デフォルトで「view」アプリケーションコンポーネントが使用されます。

public yii\base\View|yii\web\View getView ( )
戻り値 yii\base\View|yii\web\View

ビューまたはビューファイルをレンダリングするために使用できるビューオブジェクト。

                public function getView()
{
    if ($this->_view === null) {
        $this->_view = Yii::$app->getView();
    }
    return $this->_view;
}

            
getViewPath() publicメソッド

定義位置: yii\base\Controller::getViewPath()

このコントローラのビューファイルを含むディレクトリを返します。

デフォルトの実装では、$module$viewPathディレクトリの下にある、コントローラー$idという名前のディレクトリが返されます。

public string getViewPath ( )
戻り値 string

このコントローラのビューファイルを含むディレクトリ。

                public function getViewPath()
{
    if ($this->_viewPath === null) {
        $this->_viewPath = $this->module->getViewPath() . DIRECTORY_SEPARATOR . $this->id;
    }
    return $this->_viewPath;
}

            
globalFixtures() publicメソッド

定義位置: yii\test\FixtureTrait::globalFixtures()

異なるテストケースで共有が必要なフィクスチャを宣言します。

戻り値は、fixtures()のものと同様である必要があります。通常は、基底クラスでこのメソッドをオーバーライドする必要があります。

参照: fixtures().

public array globalFixtures ( )
戻り値 array

異なるテストケースで共有され、必要とされるフィクスチャ。

                public function globalFixtures()
{
    return [];
}

            
hasEventHandlers() publicメソッド

定義位置: yii\base\Component::hasEventHandlers()

名前付きイベントにハンドラがアタッチされているかどうかを示す値を返します。

public boolean hasEventHandlers ( $name )
$name string

イベント名

戻り値 boolean

イベントにハンドラーがアタッチされているかどうか。

                public function hasEventHandlers($name)
{
    $this->ensureBehaviors();
    if (!empty($this->_events[$name])) {
        return true;
    }
    foreach ($this->_eventWildcards as $wildcard => $handlers) {
        if (!empty($handlers) && StringHelper::matchWildcard($wildcard, $name)) {
            return true;
        }
    }
    return Event::hasHandlers($this, $name);
}

            
hasMethod() publicメソッド

定義位置: yii\base\Component::hasMethod()

メソッドが定義されているかどうかを示す値を返します。

メソッドは、以下の場合に定義されています。

  • クラスが指定された名前のメソッドを持つ場合
  • アタッチされたビヘイビアが指定された名前のメソッドを持つ場合($checkBehaviorsがtrueの場合)。
public boolean hasMethod ( $name, $checkBehaviors true )
$name string

プロパティ名

$checkBehaviors boolean

ビヘイビアのメソッドをこのコンポーネントのメソッドとして扱うかどうか

戻り値 boolean

メソッドが定義されているかどうか

                public function hasMethod($name, $checkBehaviors = true)
{
    if (method_exists($this, $name)) {
        return true;
    } elseif ($checkBehaviors) {
        $this->ensureBehaviors();
        foreach ($this->_behaviors as $behavior) {
            if ($behavior->hasMethod($name)) {
                return true;
            }
        }
    }
    return false;
}

            
hasProperty() publicメソッド

定義位置: yii\base\Component::hasProperty()

このコンポーネントのプロパティが定義されているかどうかを示す値を返します。

プロパティは、以下の場合に定義されています。

  • クラスが指定された名前と関連付けられたゲッターまたはセッターメソッドを持つ場合(この場合、プロパティ名はケースインセンシティブです)。
  • クラスに指定された名前のメンバ変数がある場合(`$checkVars` がtrueの場合)。
  • アタッチされたビヘイビアが指定された名前のプロパティを持つ場合($checkBehaviorsがtrueの場合)。

参照

public boolean hasProperty ( $name, $checkVars true, $checkBehaviors true )
$name string

プロパティ名

$checkVars boolean

メンバ変数をプロパティとして扱うかどうか

$checkBehaviors boolean

ビヘイビアのプロパティをこのコンポーネントのプロパティとして扱うかどうか

戻り値 boolean

プロパティが定義されているかどうか

                public function hasProperty($name, $checkVars = true, $checkBehaviors = true)
{
    return $this->canGetProperty($name, $checkVars, $checkBehaviors) || $this->canSetProperty($name, false, $checkBehaviors);
}

            
init() publicメソッド (バージョン2.0.36から利用可能)

定義位置: yii\base\Controller::init()

オブジェクトを初期化します。

このメソッドは、オブジェクトが指定された設定で初期化された後、コンストラクターの最後に呼び出されます。

public void init ( )

                public function init()
{
    parent::init();
    $this->request = Instance::ensure($this->request, Request::className());
    $this->response = Instance::ensure($this->response, Response::className());
}

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

定義位置: yii\test\FixtureTrait::initFixtures()

フィクスチャを初期化します。

public void initFixtures ( )

                public function initFixtures()
{
    $this->unloadFixtures();
    $this->loadFixtures();
}

            
isColorEnabled() publicメソッド

定義位置: yii\console\Controller::isColorEnabled()

ANSIカラーが有効かどうかを示す値を返します。

$colorがtrueに設定されているか、設定されておらず、ターミナルがANSIカラーをサポートしている場合にのみ、ANSIカラーが有効になります。

public boolean isColorEnabled ( $stream = \STDOUT )
$stream リソース

確認するストリーム。

戻り値 boolean

出力でANSIスタイルを有効にするかどうか。

                public function isColorEnabled($stream = \STDOUT)
{
    return $this->color === null ? Console::streamSupportsAnsiColors($stream) : $this->color;
}

            
loadFixtures() publicメソッド

定義位置: yii\test\FixtureTrait::loadFixtures()

指定されたフィクスチャをロードします。

このメソッドは、各フィクスチャオブジェクトに対してyii\test\Fixture::load()を呼び出します。

public void loadFixtures ( $fixtures null )
$fixtures yii\test\Fixture[]|null

ロードするフィクスチャ。このパラメーターが指定されていない場合、getFixtures()の戻り値が使用されます。

                public function loadFixtures($fixtures = null)
{
    if ($fixtures === null) {
        $fixtures = $this->getFixtures();
    }
    /* @var $fixture Fixture */
    foreach ($fixtures as $fixture) {
        $fixture->beforeLoad();
    }
    foreach ($fixtures as $fixture) {
        $fixture->load();
    }
    foreach (array_reverse($fixtures) as $fixture) {
        $fixture->afterLoad();
    }
}

            
needToApplyAll() publicメソッド

すべてのフィクスチャを適用する必要があるかどうかをチェックします。

public boolean needToApplyAll ( $fixture )
$fixture string

                public function needToApplyAll($fixture)
{
    return $fixture === '*';
}

            
notifyNothingToLoad() publicメソッド

入力条件に従ってロードするフィクスチャがないことをユーザーに通知します。

public void notifyNothingToLoad ( $foundFixtures, $except )
$foundFixtures array

検出されたフィクスチャの配列

$except array

ロードすべきでないフィクスチャの名前の配列

                public function notifyNothingToLoad($foundFixtures, $except)
{
    $this->stdout("Fixtures to load could not be found according given conditions:\n\n", Console::FG_RED);
    $this->stdout("Fixtures namespace is: \n", Console::FG_YELLOW);
    $this->stdout("\t" . $this->namespace . "\n", Console::FG_GREEN);
    if (count($foundFixtures)) {
        $this->stdout("\nFixtures founded under the namespace:\n\n", Console::FG_YELLOW);
        $this->outputList($foundFixtures);
    }
    if (count($except)) {
        $this->stdout("\nFixtures that will NOT be loaded: \n\n", Console::FG_YELLOW);
        $this->outputList($except);
    }
}

            
notifyNothingToUnload() publicメソッド

入力条件に従ってアンロードするフィクスチャがないことをユーザーに通知します。

public void notifyNothingToUnload ( $foundFixtures, $except )
$foundFixtures array

検出されたフィクスチャの配列

$except array

ロードすべきでないフィクスチャの名前の配列

                public function notifyNothingToUnload($foundFixtures, $except)
{
    $this->stdout("Fixtures to unload could not be found according to given conditions:\n\n", Console::FG_RED);
    $this->stdout("Fixtures namespace is: \n", Console::FG_YELLOW);
    $this->stdout("\t" . $this->namespace . "\n", Console::FG_GREEN);
    if (count($foundFixtures)) {
        $this->stdout("\nFixtures found under the namespace:\n\n", Console::FG_YELLOW);
        $this->outputList($foundFixtures);
    }
    if (count($except)) {
        $this->stdout("\nFixtures that will NOT be unloaded: \n\n", Console::FG_YELLOW);
        $this->outputList($except);
    }
}

            
off() publicメソッド

定義済み: yii\base\Component::off()

このコンポーネントから既存のイベントハンドラをデタッチします。

このメソッドはon()の反対です。

注:イベント名にワイルドカードパターンが渡された場合、このワイルドカードで登録されたハンドラのみが削除され、このワイルドカードに一致するプレーン名で登録されたハンドラは残ります。

参照:on().

public boolean off ( $name, $handler null )
$name string

イベント名

$handler callable|null

削除するイベントハンドラ。nullの場合、指定されたイベントにアタッチされているすべてのハンドラが削除されます。

戻り値 boolean

ハンドラが見つかり、デタッチされた場合

                public function off($name, $handler = null)
{
    $this->ensureBehaviors();
    if (empty($this->_events[$name]) && empty($this->_eventWildcards[$name])) {
        return false;
    }
    if ($handler === null) {
        unset($this->_events[$name], $this->_eventWildcards[$name]);
        return true;
    }
    $removed = false;
    // plain event names
    if (isset($this->_events[$name])) {
        foreach ($this->_events[$name] as $i => $event) {
            if ($event[0] === $handler) {
                unset($this->_events[$name][$i]);
                $removed = true;
            }
        }
        if ($removed) {
            $this->_events[$name] = array_values($this->_events[$name]);
            return true;
        }
    }
    // wildcard event names
    if (isset($this->_eventWildcards[$name])) {
        foreach ($this->_eventWildcards[$name] as $i => $event) {
            if ($event[0] === $handler) {
                unset($this->_eventWildcards[$name][$i]);
                $removed = true;
            }
        }
        if ($removed) {
            $this->_eventWildcards[$name] = array_values($this->_eventWildcards[$name]);
            // remove empty wildcards to save future redundant regex checks:
            if (empty($this->_eventWildcards[$name])) {
                unset($this->_eventWildcards[$name]);
            }
        }
    }
    return $removed;
}

            
on() publicメソッド

定義済み: yii\base\Component::on()

イベントにイベントハンドラをアタッチします。

イベントハンドラは有効なPHPコールバックである必要があります。いくつかの例を以下に示します。

function ($event) { ... }         // anonymous function
[$object, 'handleClick']          // $object->handleClick()
['Page', 'handleClick']           // Page::handleClick()
'handleClick'                     // global function handleClick()

イベントハンドラは次のシグネチャで定義する必要があります。

function ($event)

ここで、$eventは、イベントに関連付けられたパラメータを含むyii\base\Eventオブジェクトです。

2.0.14以降、イベント名をワイルドカードパターンとして指定できます。

$component->on('event.group.*', function ($event) {
    Yii::trace($event->name . ' is triggered.');
});

参照:off().

public void on ( $name, $handler, $data null, $append true )
$name string

イベント名

$handler callable

イベントハンドラ

$data mixed

イベントがトリガーされたときにイベントハンドラに渡されるデータ。イベントハンドラが呼び出されると、このデータはyii\base\Event::$dataからアクセスできます。

$append boolean

既存のハンドラリストの最後に新しいイベントハンドラを追加するかどうか。falseの場合、新しいハンドラは既存のハンドラリストの先頭に挿入されます。

                public function on($name, $handler, $data = null, $append = true)
{
    $this->ensureBehaviors();
    if (strpos($name, '*') !== false) {
        if ($append || empty($this->_eventWildcards[$name])) {
            $this->_eventWildcards[$name][] = [$handler, $data];
        } else {
            array_unshift($this->_eventWildcards[$name], [$handler, $data]);
        }
        return;
    }
    if ($append || empty($this->_events[$name])) {
        $this->_events[$name][] = [$handler, $data];
    } else {
        array_unshift($this->_events[$name], [$handler, $data]);
    }
}

            
optionAliases() publicメソッド (バージョン2.0.8以降で利用可能)

オプションのエイリアス名を返します。

子クラスはこのメソッドをオーバーライドして、エイリアスオプションを指定できます。

public array optionAliases ( )
戻り値 array

アクションに対して有効なオプションのエイリアス名。キーはオプションのエイリアス名、値はオプション名です。

                public function optionAliases()
{
    return array_merge(parent::optionAliases(), [
        'g' => 'globalFixtures',
        'n' => 'namespace',
    ]);
}

            
options() publicメソッド

アクション(id)の有効なオプションの名前を返します。オプションには、オプション名と同じ名前のパブリックメンバ変数の存在が必要です。

子クラスはこのメソッドをオーバーライドして、可能なオプションを指定できます。

オプションを介して設定された値は、beforeAction()が呼び出されるまで使用できません。

public string[] options ( $actionID )
$actionID string

現在のリクエストのアクションID。

戻り値 string[]

アクションに対して有効なオプションの名前

                public function options($actionID)
{
    return array_merge(parent::options($actionID), [
        'namespace', 'globalFixtures',
    ]);
}

            
parseDocCommentDetail() protectedメソッド

定義済み: yii\console\Controller::parseDocCommentDetail()

docblockから完全な説明を返します。

protected string parseDocCommentDetail ( $reflection )
$reflection ReflectionClass|ReflectionProperty|ReflectionFunctionAbstract

                protected function parseDocCommentDetail($reflection)
{
    $comment = strtr(trim(preg_replace('/^\s*\**([ \t])?/m', '', trim($reflection->getDocComment(), '/'))), "\r", '');
    if (preg_match('/^\s*@\w+/m', $comment, $matches, PREG_OFFSET_CAPTURE)) {
        $comment = trim(substr($comment, 0, $matches[0][1]));
    }
    if ($comment !== '') {
        return rtrim(Console::renderColoredString(Console::markdownToAnsi($comment)));
    }
    return '';
}

            
parseDocCommentSummary() protectedメソッド

定義済み: yii\console\Controller::parseDocCommentSummary()

docblockの最初の行を返します。

protected string parseDocCommentSummary ( $reflection )
$reflection ReflectionClass|ReflectionProperty|ReflectionFunctionAbstract

                protected function parseDocCommentSummary($reflection)
{
    $docLines = preg_split('~\R~u', $reflection->getDocComment());
    if (isset($docLines[1])) {
        return trim($docLines[1], "\t *");
    }
    return '';
}

            
parseDocCommentTags() protectedメソッド

定義済み: yii\console\Controller::parseDocCommentTags()

コメントブロックをタグに解析します。

protected array parseDocCommentTags ( $reflection )
$reflection ReflectionClass|ReflectionProperty|ReflectionFunctionAbstract

コメントブロック

戻り値 array

解析されたタグ

                protected function parseDocCommentTags($reflection)
{
    $comment = $reflection->getDocComment();
    $comment = "@description \n" . strtr(trim(preg_replace('/^\s*\**([ \t])?/m', '', trim($comment, '/'))), "\r", '');
    $parts = preg_split('/^\s*@/m', $comment, -1, PREG_SPLIT_NO_EMPTY);
    $tags = [];
    foreach ($parts as $part) {
        if (preg_match('/^(\w+)(.*)/ms', trim($part), $matches)) {
            $name = $matches[1];
            if (!isset($tags[$name])) {
                $tags[$name] = trim($matches[2]);
            } elseif (is_array($tags[$name])) {
                $tags[$name][] = trim($matches[2]);
            } else {
                $tags[$name] = [$tags[$name], trim($matches[2])];
            }
        }
    }
    return $tags;
}

            
prompt() publicメソッド

定義済み: yii\console\Controller::prompt()

ユーザーに入力を促し、それを検証します。

public string prompt ( $text, $options = [] )
$text string

プロンプト文字列

$options array

入力値を検証するためのオプション

  • required: 必須入力かどうか
  • default: ユーザーが入力しなかった場合のデフォルト値
  • pattern: ユーザー入力の検証に使用する正規表現パターン
  • validator: 入力を検証するためのコールバック関数。関数は2つのパラメータを受け取る必要があります。
    • $input: 検証するユーザー入力
    • $error: 検証に失敗した場合、参照渡しで渡されるエラー値。

バリデーター関数を使用してpromptメソッドを使用する方法の例。

$code = $this->prompt('Enter 4-Chars-Pin', ['required' => true, 'validator' => function($input, &$error) {
    if (strlen($input) !== 4) {
        $error = 'The Pin must be exactly 4 chars!';
        return false;
    }
    return true;
}]);
戻り値 string

ユーザー入力

                public function prompt($text, $options = [])
{
    if ($this->interactive) {
        return Console::prompt($text, $options);
    }
    return isset($options['default']) ? $options['default'] : '';
}

            
render() publicメソッド

定義されている場所: yii\base\Controller::render()

ビューをレンダリングし、レイアウトが利用可能な場合は適用します。

レンダリングされるビューは、以下のいずれかの形式で指定できます。

  • パスエイリアス (例: "@app/views/site/index")
  • アプリケーション内の絶対パス (例: "//site/index"): ビュー名がダブルスラッシュで始まる場合。実際のビューファイルは、アプリケーションのビューパスの下で検索されます。
  • モジュール内の絶対パス (例: "/site/index"): ビュー名がシングルスラッシュで始まる場合。実際のビューファイルは、ビューパス$moduleの下で検索されます。
  • 相対パス (例: "index"): 実際のビューファイルは$viewPathの下で検索されます。

適用するレイアウトを決定するために、以下の2つの手順が行われます。

  1. 最初の手順では、レイアウト名とコンテキストモジュールを決定します。
  • $layoutが文字列として指定されている場合、レイアウト名として使用し、$moduleをコンテキストモジュールとして使用します。
  • $layoutがnullの場合、このコントローラーのすべての祖先モジュールを検索し、layoutがnullでない最初のモジュールを見つけます。レイアウトと対応するモジュールが、それぞれレイアウト名とコンテキストモジュールとして使用されます。そのようなモジュールが見つからない場合、または対応するレイアウトが文字列でない場合、falseを返し、適用可能なレイアウトがないことを意味します。
  1. 2番目の手順では、先に検出されたレイアウト名とコンテキストモジュールに従って、実際のレイアウトファイルを決定します。レイアウト名は、
  • パスエイリアス (例: "@app/views/layouts/main")
  • 絶対パス (例: "/main"): レイアウト名がスラッシュで始まる場合。実際のレイアウトファイルは、アプリケーションのレイアウトパスの下で検索されます。
  • 相対パス (例: "main"): 実際のレイアウトファイルは、コンテキストモジュールのレイアウトパスの下で検索されます。

レイアウト名にファイル拡張子が含まれていない場合、デフォルトの.phpが使用されます。

public string render ( $view, $params = [] )
$view string

ビュー名。

$params array

ビューで使用可能にするパラメータ(名前と値のペア)。これらのパラメータはレイアウトでは使用できません。

戻り値 string

レンダリング結果。

例外 yii\base\InvalidArgumentException

ビューファイルまたはレイアウトファイルが存在しない場合。

                public function render($view, $params = [])
{
    $content = $this->getView()->render($view, $params, $this);
    return $this->renderContent($content);
}

            
renderContent() publicメソッド (バージョン2.0.1から利用可能)

定義されている場所: yii\base\Controller::renderContent()

レイアウトを適用して静的な文字列をレンダリングします。

public string renderContent ( $content )
$content string

レンダリングされる静的文字列

戻り値 string

与えられた静的文字列を$content変数として持つレイアウトのレンダリング結果。レイアウトが無効になっている場合、文字列が返されます。

                public function renderContent($content)
{
    $layoutFile = $this->findLayoutFile($this->getView());
    if ($layoutFile !== false) {
        return $this->getView()->renderFile($layoutFile, ['content' => $content], $this);
    }
    return $content;
}

            
renderFile() publicメソッド

定義されている場所: yii\base\Controller::renderFile()

ビューファイルをレンダリングします。

public string renderFile ( $file, $params = [] )
$file string

レンダリングするビューファイル。ファイルパスまたはパスエイリアスのいずれかです。

$params array

ビューで使用可能にするパラメータ(名前と値のペア)。

戻り値 string

レンダリング結果。

例外 yii\base\InvalidArgumentException

ビューファイルが存在しない場合。

                public function renderFile($file, $params = [])
{
    return $this->getView()->renderFile($file, $params, $this);
}

            
renderPartial() publicメソッド

定義されている場所: yii\base\Controller::renderPartial()

レイアウトを適用せずにビューをレンダリングします。

このメソッドは、レイアウトを適用しないという点でrender()とは異なります。

public string renderPartial ( $view, $params = [] )
$view string

ビュー名。ビュー名の指定方法については、render()を参照してください。

$params array

ビューで使用可能にするパラメータ(名前と値のペア)。

戻り値 string

レンダリング結果。

例外 yii\base\InvalidArgumentException

ビューファイルが存在しない場合。

                public function renderPartial($view, $params = [])
{
    return $this->getView()->render($view, $params, $this);
}

            
run() publicメソッド

定義されている場所: yii\base\Controller::run()

ルートで指定されたリクエストを実行します。

ルートは、このコントローラー内のアクションのID、またはモジュールID、コントローラーID、アクションIDからなる完全なルートのいずれかです。ルートがスラッシュ '/' で始まる場合、ルートの解析はアプリケーションから開始されます。それ以外の場合は、このコントローラーの親モジュールから開始されます。

runAction()も参照してください。

public mixed run ( $route, $params = [] )
$route string

処理するルート(例: 'view'、'comment/view'、'/admin/comment/view')。

$params array

アクションに渡すパラメータ。

戻り値 mixed

アクションの結果。

                public function run($route, $params = [])
{
    $pos = strpos($route, '/');
    if ($pos === false) {
        return $this->runAction($route, $params);
    } elseif ($pos > 0) {
        return $this->module->runAction($route, $params);
    }
    return Yii::$app->runAction(ltrim($route, '/'), $params);
}

            
runAction() publicメソッド

定義されている場所: yii\console\Controller::runAction()

指定されたアクションIDとパラメータを使用してアクションを実行します。

アクションIDが空の場合、このメソッドは$defaultActionを使用します。

createAction()も参照してください。

public integer runAction ( $id, $params = [] )
$id string

実行するアクションのID。

$params array

アクションに渡すパラメータ(名前と値のペア)。

戻り値 integer

アクション実行の状態。0は正常、それ以外の値は異常。

例外 yii\base\InvalidRouteException

要求されたアクションIDをアクションに正常に解決できない場合。

例外 yii\console\Exception

不明なオプションまたは不足している引数がある場合

                public function runAction($id, $params = [])
{
    if (!empty($params)) {
        // populate options here so that they are available in beforeAction().
        $options = $this->options($id === '' ? $this->defaultAction : $id);
        if (isset($params['_aliases'])) {
            $optionAliases = $this->optionAliases();
            foreach ($params['_aliases'] as $name => $value) {
                if (array_key_exists($name, $optionAliases)) {
                    $params[$optionAliases[$name]] = $value;
                } else {
                    $message = Yii::t('yii', 'Unknown alias: -{name}', ['name' => $name]);
                    if (!empty($optionAliases)) {
                        $aliasesAvailable = [];
                        foreach ($optionAliases as $alias => $option) {
                            $aliasesAvailable[] = '-' . $alias . ' (--' . $option . ')';
                        }
                        $message .= '. ' . Yii::t('yii', 'Aliases available: {aliases}', [
                            'aliases' => implode(', ', $aliasesAvailable)
                        ]);
                    }
                    throw new Exception($message);
                }
            }
            unset($params['_aliases']);
        }
        foreach ($params as $name => $value) {
            // Allow camelCase options to be entered in kebab-case
            if (!in_array($name, $options, true) && strpos($name, '-') !== false) {
                $kebabName = $name;
                $altName = lcfirst(Inflector::id2camel($kebabName));
                if (in_array($altName, $options, true)) {
                    $name = $altName;
                }
            }
            if (in_array($name, $options, true)) {
                $default = $this->$name;
                if (is_array($default) && is_string($value)) {
                    $this->$name = preg_split('/\s*,\s*(?![^()]*\))/', $value);
                } elseif ($default !== null) {
                    settype($value, gettype($default));
                    $this->$name = $value;
                } else {
                    $this->$name = $value;
                }
                $this->_passedOptions[] = $name;
                unset($params[$name]);
                if (isset($kebabName)) {
                    unset($params[$kebabName]);
                }
            } elseif (!is_int($name)) {
                $message = Yii::t('yii', 'Unknown option: --{name}', ['name' => $name]);
                if (!empty($options)) {
                    $message .= '. ' . Yii::t('yii', 'Options available: {options}', ['options' => '--' . implode(', --', $options)]);
                }
                throw new Exception($message);
            }
        }
    }
    if ($this->help) {
        $route = $this->getUniqueId() . '/' . $id;
        return Yii::$app->runAction('help', [$route]);
    }
    return parent::runAction($id, $params);
}

            
select() publicメソッド

定義されている場所: yii\console\Controller::select()

ユーザーに選択オプションを提供します。「?」を入力すると、選択可能なオプションとその説明のリストが表示されます。

public string select ( $prompt, $options = [], $default null )
$prompt string

プロンプトメッセージ

$options array

選択可能なオプションのキーと値の配列

$default string|null

ユーザーがオプションを選択しなかった場合に使用する値。デフォルトがnullの場合、ユーザーはオプションを選択する必要があります。

戻り値 string

ユーザーが選択したオプション文字

バージョン 説明
2.0.49 $default引数を追加しました。

                public function select($prompt, $options = [], $default = null)
{
    if ($this->interactive) {
        return Console::select($prompt, $options, $default);
    }
    return $default;
}

            
setView() publicメソッド

定義されている場所: yii\base\Controller::setView()

このコントローラで使用されるビューオブジェクトを設定します。

public void setView ( $view )
$view yii\base\View|yii\web\View

ビューまたはビューファイルをレンダリングするために使用できるビューオブジェクト。

                public function setView($view)
{
    $this->_view = $view;
}

            
setViewPath() publicメソッド (バージョン2.0.7から利用可能)

定義されている場所: yii\base\Controller::setViewPath()

ビューファイルを含むディレクトリを設定します。

public void setViewPath ( $path )
$path string

ビューファイルのルートディレクトリ。

例外 yii\base\InvalidArgumentException

ディレクトリが無効な場合

                public function setViewPath($path)
{
    $this->_viewPath = Yii::getAlias($path);
}

            
stderr() publicメソッド

定義されている場所: yii\console\Controller::stderr()

STDERRに文字列を出力します。

yii\helpers\Consoleで定義されている定数を使用して追加のパラメータを渡すことで、ANSIコードを使用して文字列をフォーマットすることもできます。

$this->stderr('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE);
public integer|boolean stderr ( $string )
$string string

出力する文字列

戻り値 integer|boolean

出力されたバイト数、またはエラー発生時はfalse

                public function stderr($string)
{
    if ($this->isColorEnabled(\STDERR)) {
        $args = func_get_args();
        array_shift($args);
        $string = Console::ansiFormat($string, $args);
    }
    return fwrite(\STDERR, $string);
}

            
stdout() publicメソッド

定義されている場所: yii\console\Controller::stdout()

STDOUTに文字列を出力します。

yii\helpers\Consoleで定義されている定数を使用して追加のパラメータを渡すことで、ANSIコードを使用して文字列をフォーマットすることもできます。

$this->stdout('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE);
public integer|boolean stdout ( $string )
$string string

出力する文字列

戻り値 integer|boolean

出力されたバイト数、またはエラー発生時はfalse

                public function stdout($string)
{
    if ($this->isColorEnabled()) {
        $args = func_get_args();
        array_shift($args);
        $string = Console::ansiFormat($string, $args);
    }
    return Console::stdout($string);
}

            
trigger() publicメソッド

定義されている場所: yii\base\Component::trigger()

イベントをトリガーします。

このメソッドはイベントの発生を表します。クラスレベルのハンドラを含む、イベントにアタッチされているすべてのハンドラを呼び出します。

public void trigger ( $name, yii\base\Event $event null )
$name string

イベント名

$event yii\base\Event|null

イベントインスタンス。設定されていない場合、デフォルトのyii\base\Eventオブジェクトが作成されます。

                public function trigger($name, Event $event = null)
{
    $this->ensureBehaviors();
    $eventHandlers = [];
    foreach ($this->_eventWildcards as $wildcard => $handlers) {
        if (StringHelper::matchWildcard($wildcard, $name)) {
            $eventHandlers[] = $handlers;
        }
    }
    if (!empty($this->_events[$name])) {
        $eventHandlers[] = $this->_events[$name];
    }
    if (!empty($eventHandlers)) {
        $eventHandlers = call_user_func_array('array_merge', $eventHandlers);
        if ($event === null) {
            $event = new Event();
        }
        if ($event->sender === null) {
            $event->sender = $this;
        }
        $event->handled = false;
        $event->name = $name;
        foreach ($eventHandlers as $handler) {
            $event->data = $handler[1];
            call_user_func($handler[0], $event);
            // stop further handling if the event is handled
            if ($event->handled) {
                return;
            }
        }
    }
    // invoke class-level attached handlers
    Event::trigger($this, $name, $event);
}

            
unloadFixtures() publicメソッド

定義されている場所: yii\test\FixtureTrait::unloadFixtures()

指定されたフィクスチャをアンロードします。

このメソッドは、各フィクスチャオブジェクトに対してyii\test\Fixture::unload()を呼び出します。

public void unloadFixtures ( $fixtures null )
$fixtures yii\test\Fixture[]|null

ロードするフィクスチャ。このパラメーターが指定されていない場合、getFixtures()の戻り値が使用されます。

                public function unloadFixtures($fixtures = null)
{
    if ($fixtures === null) {
        $fixtures = $this->getFixtures();
    }
    /* @var $fixture Fixture */
    foreach ($fixtures as $fixture) {
        $fixture->beforeUnload();
    }
    $fixtures = array_reverse($fixtures);
    foreach ($fixtures as $fixture) {
        $fixture->unload();
    }
    foreach ($fixtures as $fixture) {
        $fixture->afterUnload();
    }
}