0 關注者

抽象類別 yii\console\controllers\BaseMigrateController

繼承yii\console\controllers\BaseMigrateController » yii\console\Controller » yii\base\Controller » yii\base\Component » yii\base\BaseObject
實作yii\base\Configurable, yii\base\ViewContextInterface
子類別yii\console\controllers\MigrateController
自版本起可用2.0
原始碼 https://github.com/yiisoft/yii2/blob/master/framework/console/controllers/BaseMigrateController.php

BaseMigrateController 是遷移控制器 (migrate controllers) 的基底類別。

公開屬性

隱藏繼承的屬性

屬性 類型 描述 定義於
$action yii\base\Action|null 目前正在執行的動作 (action)。 yii\base\Controller
$behaviors yii\base\Behavior[] 附加到此元件的行為 (behaviors) 列表。 yii\base\Component
$color boolean|null 是否在輸出中啟用 ANSI 彩色。 yii\console\Controller
$compact boolean 指示是否應壓縮主控台輸出。 yii\console\controllers\BaseMigrateController
$defaultAction string 預設命令動作 (command action)。 yii\console\controllers\BaseMigrateController
$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 將應用於此控制器視圖 (views) 的版面配置 (layout) 名稱。 yii\base\Controller
$migrationNamespaces array 包含遷移類別 (migration classes) 的命名空間列表。 yii\console\controllers\BaseMigrateController
$migrationPath string|array|null 包含遷移類別 (migration classes) 的目錄。 yii\console\controllers\BaseMigrateController
$module yii\base\Module 此控制器所屬的模組 (module)。 yii\base\Controller
$modules yii\base\Module[] 此控制器所在的所有上層模組 (ancestor modules)。 yii\base\Controller
$newFileMode integer|null 為新產生的遷移檔案設定的權限。 yii\console\controllers\BaseMigrateController
$newFileOwnership string|integer|null 為新產生的遷移檔案設定的使用者和/或群組所有權。 yii\console\controllers\BaseMigrateController
$passedOptionValues array 對應於傳遞選項 (passed options) 的屬性。 yii\console\Controller
$passedOptions array 執行期間傳遞的選項名稱。 yii\console\Controller
$request yii\base\Request|array|string 請求 (request)。 yii\base\Controller
$response yii\base\Response|array|string 回應 (response)。 yii\base\Controller
$route string 目前請求的路由 (module ID、controller ID 和 action ID)。 yii\base\Controller
$silentExitOnException boolean|null 如果為 true - 腳本在發生例外情況時以 ExitCode::OK 結束。 yii\console\Controller
$templateFile string 用於產生新遷移的範本檔案。 yii\console\controllers\BaseMigrateController
$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
actionCreate() 建立新的遷移。 yii\console\controllers\BaseMigrateController
actionDown() 透過還原舊遷移來降級應用程式。 yii\console\controllers\BaseMigrateController
actionFresh() 刪除所有表格和相關約束。從頭開始遷移。 yii\console\controllers\BaseMigrateController
actionHistory() 顯示遷移歷史紀錄。 yii\console\controllers\BaseMigrateController
actionMark() 將遷移歷史紀錄修改為指定的版本。 yii\console\controllers\BaseMigrateController
actionNew() 顯示未套用的新遷移。 yii\console\controllers\BaseMigrateController
actionRedo() 重做最後幾次遷移。 yii\console\controllers\BaseMigrateController
actionTo() 升級或降級到指定的版本。 yii\console\controllers\BaseMigrateController
actionUp() 透過套用新遷移來升級應用程式。 yii\console\controllers\BaseMigrateController
actions() 宣告控制器的外部動作。 yii\base\Controller
afterAction() 此方法在動作執行後立即調用。 yii\base\Controller
ansiFormat() 使用 ANSI 代碼格式化字串。 yii\console\Controller
attachBehavior() 將行為附加到此組件。 yii\base\Component
attachBehaviors() 將行為列表附加到組件。 yii\base\Component
beforeAction() 此方法在動作即將執行前(在所有可能的篩選器之後)調用。它檢查 $migrationPath 是否存在。 yii\console\controllers\BaseMigrateController
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
getActionArgsHelp() 返回動作的匿名參數的說明資訊。 yii\console\Controller
getActionHelp() 返回指定動作的詳細說明資訊。 yii\console\Controller
getActionHelpSummary() 返回描述指定動作的單行簡短摘要。 yii\console\Controller
getActionOptionsHelp() 返回動作選項的說明資訊。 yii\console\Controller
getBehavior() 返回指定的行為物件。 yii\base\Component
getBehaviors() 返回附加到此組件的所有行為。 yii\base\Component
getHelp() 返回此控制器的說明資訊。 yii\console\Controller
getHelpSummary() 返回描述此控制器的單行簡短摘要。 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
hasEventHandlers() 返回一個值,指示是否有名稱事件附加任何處理程序。 yii\base\Component
hasMethod() 返回一個值,指示是否已定義方法。 yii\base\Component
hasProperty() 返回一個值,指示是否為此組件定義了屬性。 yii\base\Component
init() 初始化物件。 yii\base\Controller
isColorEnabled() 返回一個值,指示是否啟用 ANSI 彩色。 yii\console\Controller
off() 從此組件分離現有的事件處理程序。 yii\base\Component
on() 將事件處理程序附加到事件。 yii\base\Component
optionAliases() 返回選項別名。 yii\console\Controller
options() 返回動作 (id) 的有效選項名稱。選項需要存在一個公共成員變數,其名稱為選項名稱。 yii\console\controllers\BaseMigrateController
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

保護方法

隱藏繼承方法

方法 描述 定義於
addMigrationHistory() 將新的遷移條目添加到歷史紀錄中。 yii\console\controllers\BaseMigrateController
bindInjectedParams() 根據動作方法簽名中的類型和名稱填寫參數。 yii\base\Controller
createMigration() 建立新的遷移實例。 yii\console\controllers\BaseMigrateController
generateMigrationSourceCode() 產生新的遷移原始碼 PHP 程式碼。 yii\console\controllers\BaseMigrateController
getActionMethodReflection() yii\console\Controller
getMigrationHistory() 返回遷移歷史紀錄。 yii\console\controllers\BaseMigrateController
getMigrationNameLimit() 返回遷移的最大名稱長度。 yii\console\controllers\BaseMigrateController
getNewMigrations() 返回未套用的遷移。 yii\console\controllers\BaseMigrateController
includeMigrationFile() 包含給定遷移類別名稱的遷移檔案。 yii\console\controllers\BaseMigrateController
migrateDown() 使用指定的遷移類別降級。 yii\console\controllers\BaseMigrateController
migrateToTime() 遷移到過去指定的套用時間。 yii\console\controllers\BaseMigrateController
migrateToVersion() 遷移到特定版本。 yii\console\controllers\BaseMigrateController
migrateUp() 使用指定的遷移類別升級。 yii\console\controllers\BaseMigrateController
parseDocCommentDetail() 從 docblock 返回完整描述。 yii\console\Controller
parseDocCommentSummary() 返回 docblock 的第一行。 yii\console\Controller
parseDocCommentTags() 將註解區塊解析為標籤。 yii\console\Controller
removeMigrationHistory() 從歷史紀錄中移除現有的遷移。 yii\console\controllers\BaseMigrateController
truncateDatabase() 截斷資料庫。 yii\console\controllers\BaseMigrateController

事件

隱藏繼承事件

事件 類型 描述 定義於
EVENT_AFTER_ACTION yii\base\ActionEvent 在執行控制器動作後立即引發的事件。 yii\base\Controller
EVENT_BEFORE_ACTION yii\base\ActionEvent 在執行控制器動作前立即引發的事件。 yii\base\Controller

常數

隱藏繼承常數

常數 描述 定義於
BASE_MIGRATION 'm000000_000000_base' 標記整個遷移歷史紀錄開始的虛擬遷移名稱。 yii\console\controllers\BaseMigrateController
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

屬性詳細資訊

隱藏繼承的屬性

$compact 公共屬性 (自 2.0.13 版本起可用)

指示是否應壓縮主控台輸出。如果設定為 true,則遷移中執行的個別命令將不會輸出到主控台。預設值為 false,換句話說,預設情況下輸出是完全詳細的。

public boolean $compact false
$defaultAction 公共屬性

預設命令動作 (command action)。

public string $defaultAction 'up'
$migrationNamespaces 公共屬性 (自 2.0.10 版本起可用)

包含遷移類別 (migration classes) 的命名空間列表。

遷移命名空間應該可以解析為路徑別名,如果以 @ 作為前綴。例如,如果您指定命名空間 app\migrations,則程式碼 Yii::getAlias('@app/migrations') 應該能夠返回此命名空間所指目錄的檔案路徑。這與 autoloading conventions of Yii 的自動載入慣例一致。

例如

[
    'app\migrations',
    'some\extension\migrations',
]

另請參閱 $migrationPath

$migrationPath 公共屬性

包含遷移類別的目錄。這可以是 path alias 路徑別名或目錄路徑。

位於此路徑的遷移類別應在不使用命名空間的情況下宣告。如果您正在使用命名空間遷移,請使用 $migrationNamespaces 屬性。

如果您已設定 $migrationNamespaces,您可以將此欄位設定為 null,以停用未使用命名空間的遷移。

自 2.0.12 版本起,您也可以指定遷移路徑的陣列,應在其中搜尋要載入的遷移。這主要用於支援提供無命名空間遷移的舊擴充功能,並採用命名空間遷移的新功能,同時保留現有的遷移。

一般而言,若要從不同位置載入遷移,$migrationNamespaces 是較佳的解決方案,因為遷移名稱包含遷移在歷史紀錄中的來源,而使用多個遷移路徑時則不然。

另請參閱 $migrationNamespaces

public string|array|null $migrationPath = [
    
'@app/migrations',
]
$newFileMode 公共屬性 (自 2.0.43 版本起可用)

為新產生的遷移檔案設定的權限。此值將由 PHP chmod() 函數使用。不會套用 umask。如果未設定,則權限將由目前環境決定。

public integer|null $newFileMode null
$newFileOwnership 公共屬性 (自 2.0.43 版本起可用)

為新產生的遷移檔案設定的使用者和/或群組所有權。如果未設定,則所有權將由目前環境決定。

另請參閱 yii\helpers\FileHelper::changeOwnership()

$templateFile 公共屬性

用於產生新遷移的範本檔案。這可以是 path alias 路徑別名(例如 "@app/migrations/template.php")或檔案路徑。

public string $templateFile null

方法詳細資訊

隱藏繼承方法

__call() 公共方法

定義於: 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() 公共方法

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

此方法在物件透過複製現有物件建立後呼叫。

它會移除所有行為,因為它們附加到舊物件。

public void __clone ( )

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

            
__construct() 公共方法
public void __construct ( $id, $module, $config = [] )
$id string

此控制器的 ID。

$module yii\base\Module

此控制器所屬的模組 (module)。

$config array

將用於初始化物件屬性的名稱-值對。

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

            
__get() 公共方法

定義於: yii\base\Component::__get()

返回組件屬性的值。

此方法將依以下順序檢查並採取相應措施

  • 由 getter 定義的屬性:返回 getter 結果
  • 行為的屬性:返回行為屬性值

請勿直接呼叫此方法,因為它是 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() 公共方法

定義於: yii\base\Component::__isset()

檢查屬性是否已設定,即已定義且非 null。

此方法將依以下順序檢查並採取相應措施

  • 由 setter 定義的屬性:返回屬性是否已設定
  • 行為的屬性:返回屬性是否已設定
  • 對於不存在的屬性,返回 false

請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 isset($component->property) 時,它會被隱式呼叫。

另請參閱 https://php.dev.org.tw/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() 公共方法

定義於: yii\base\Component::__set()

設定組件屬性的值。

此方法將依以下順序檢查並採取相應措施

  • 由 setter 定義的屬性:設定屬性值
  • 格式為 "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() 公共方法

定義於: yii\base\Component::__unset()

將組件屬性設定為 null。

此方法將依以下順序檢查並採取相應措施

  • 由 setter 定義的屬性:將屬性值設定為 null
  • 行為的屬性:將屬性值設定為 null

請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 unset($component->property) 時,它會被隱式呼叫。

另請參閱 https://php.dev.org.tw/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);
}

            
actionCreate() 公共方法

建立新的遷移。

此命令使用可用的遷移範本建立新的遷移。使用此命令後,開發人員應修改建立的遷移骨架,填寫實際的遷移邏輯。

yii migrate/create create_user_table

為了產生命名空間遷移,您應該在遷移名稱之前指定命名空間。請注意,反斜線 (`\`) 通常被視為 shell 中的特殊字元,因此您需要正確地逸出它,以避免 shell 錯誤或不正確的行為。例如

yii migrate/create app\\migrations\\createUserTable

如果未設定 $migrationPath 且未提供命名空間,則將使用 $migrationNamespaces 的第一個條目。

public void actionCreate ( $name )
$name string

新遷移的名稱。這應該僅包含字母、數字、底線和/或反斜線。

注意:如果遷移名稱是特殊形式,例如 create_xxx 或 drop_xxx,則產生的遷移檔案將包含額外的程式碼,在本例中用於建立/刪除表格。

拋出 yii\console\Exception

如果名稱參數無效。

                public function actionCreate($name)
{
    if (!preg_match('/^[\w\\\\]+$/', $name)) {
        throw new Exception('The migration name should contain letters, digits, underscore and/or backslash characters only.');
    }
    list($namespace, $className) = $this->generateClassName($name);
    // Abort if name is too long
    $nameLimit = $this->getMigrationNameLimit();
    if ($nameLimit !== null && strlen($className) > $nameLimit) {
        throw new Exception('The migration name is too long.');
    }
    $migrationPath = $this->findMigrationPath($namespace);
    $file = $migrationPath . DIRECTORY_SEPARATOR . $className . '.php';
    if ($this->confirm("Create new migration '$file'?")) {
        $content = $this->generateMigrationSourceCode([
            'name' => $name,
            'className' => $className,
            'namespace' => $namespace,
        ]);
        FileHelper::createDirectory($migrationPath);
        if (file_put_contents($file, $content, LOCK_EX) === false) {
            $this->stdout("Failed to create new migration.\n", Console::FG_RED);
            return ExitCode::IOERR;
        }
        FileHelper::changeOwnership($file, $this->newFileOwnership, $this->newFileMode);
        $this->stdout("New migration created successfully.\n", Console::FG_GREEN);
    }
    return ExitCode::OK;
}

            
actionDown() 公共方法

透過還原舊遷移來降級應用程式。

例如,

yii migrate/down     # revert the last migration
yii migrate/down 3   # revert the last 3 migrations
yii migrate/down all # revert all migrations
public integer actionDown ( $limit 1 )
$limit integer|string

要還原的遷移數量。預設值為 1,表示將還原最後套用的遷移。當值為 "all" 時,將還原所有遷移。

返回 integer

動作執行的狀態。0 表示正常,其他值表示異常。

拋出 yii\console\Exception

如果指定的步驟數小於 1。

                public function actionDown($limit = 1)
{
    if ($limit === 'all') {
        $limit = null;
    } else {
        $limit = (int) $limit;
        if ($limit < 1) {
            throw new Exception('The step argument must be greater than 0.');
        }
    }
    $migrations = $this->getMigrationHistory($limit);
    if (empty($migrations)) {
        $this->stdout("No migration has been done before.\n", Console::FG_YELLOW);
        return ExitCode::OK;
    }
    $migrations = array_keys($migrations);
    $n = count($migrations);
    $this->stdout("Total $n " . ($n === 1 ? 'migration' : 'migrations') . " to be reverted:\n", Console::FG_YELLOW);
    foreach ($migrations as $migration) {
        $this->stdout("\t$migration\n");
    }
    $this->stdout("\n");
    $reverted = 0;
    if ($this->confirm('Revert the above ' . ($n === 1 ? 'migration' : 'migrations') . '?')) {
        foreach ($migrations as $migration) {
            if (!$this->migrateDown($migration)) {
                $this->stdout("\n$reverted from $n " . ($reverted === 1 ? 'migration was' : 'migrations were') . " reverted.\n", Console::FG_RED);
                $this->stdout("\nMigration failed. The rest of the migrations are canceled.\n", Console::FG_RED);
                return ExitCode::UNSPECIFIED_ERROR;
            }
            $reverted++;
        }
        $this->stdout("\n$n " . ($n === 1 ? 'migration was' : 'migrations were') . " reverted.\n", Console::FG_GREEN);
        $this->stdout("\nMigrated down successfully.\n", Console::FG_GREEN);
    }
    return ExitCode::OK;
}

            
actionFresh() 公共方法 (自 2.0.13 版本起可用)

刪除所有表格和相關約束。從頭開始遷移。

yii migrate/fresh
public void actionFresh ( )

                public function actionFresh()
{
    if (YII_ENV_PROD) {
        $this->stdout("YII_ENV is set to 'prod'.\nRefreshing migrations is not possible on production systems.\n");
        return ExitCode::OK;
    }
    if ($this->confirm("Are you sure you want to drop all tables and related constraints and start the migration from the beginning?\nAll data will be lost irreversibly!")) {
        $this->truncateDatabase();
        return $this->actionUp();
    }
    $this->stdout('Action was cancelled by user. Nothing has been performed.');
    return ExitCode::OK;
}

            
actionHistory() 公共方法

顯示遷移歷史紀錄。

此命令將顯示到目前為止已套用的遷移列表。例如,

yii migrate/history     # showing the last 10 migrations
yii migrate/history 5   # showing the last 5 migrations
yii migrate/history all # showing the whole history
public void actionHistory ( $limit 10 )
$limit integer|string

要顯示的最大遷移數量。如果它是 "all",將顯示整個遷移歷史紀錄。

拋出 yii\console\Exception

如果傳遞了無效的限制值

                public function actionHistory($limit = 10)
{
    if ($limit === 'all') {
        $limit = null;
    } else {
        $limit = (int) $limit;
        if ($limit < 1) {
            throw new Exception('The limit must be greater than 0.');
        }
    }
    $migrations = $this->getMigrationHistory($limit);
    if (empty($migrations)) {
        $this->stdout("No migration has been done before.\n", Console::FG_YELLOW);
    } else {
        $n = count($migrations);
        if ($limit > 0) {
            $this->stdout("Showing the last $n applied " . ($n === 1 ? 'migration' : 'migrations') . ":\n", Console::FG_YELLOW);
        } else {
            $this->stdout("Total $n " . ($n === 1 ? 'migration has' : 'migrations have') . " been applied before:\n", Console::FG_YELLOW);
        }
        foreach ($migrations as $version => $time) {
            $this->stdout("\t(" . date('Y-m-d H:i:s', $time) . ') ' . $version . "\n");
        }
    }
    return ExitCode::OK;
}

            
actionMark() 公共方法

將遷移歷史紀錄修改為指定的版本。

不會執行實際的遷移。

yii migrate/mark 101129_185401                        # using timestamp
yii migrate/mark m101129_185401_create_user_table     # using full name
yii migrate/mark app\migrations\M101129185401CreateUser # using full namespace name
yii migrate/mark m000000_000000_base # reset the complete migration history
public integer actionMark ( $version )
$version string

應標記遷移歷史紀錄的版本。這可以是時間戳記或遷移的完整名稱。您可以指定名稱 m000000_000000_base 將遷移歷史紀錄設定為未套用任何遷移的狀態。

返回 integer

CLI 退出代碼

拋出 yii\console\Exception

如果版本參數無效或找不到版本。

                public function actionMark($version)
{
    $originalVersion = $version;
    if (($namespaceVersion = $this->extractNamespaceMigrationVersion($version)) !== false) {
        $version = $namespaceVersion;
    } elseif (($migrationName = $this->extractMigrationVersion($version)) !== false) {
        $version = $migrationName;
    } elseif ($version !== static::BASE_MIGRATION) {
        throw new Exception("The version argument must be either a timestamp (e.g. 101129_185401)\nor the full name of a migration (e.g. m101129_185401_create_user_table)\nor the full name of a namespaced migration (e.g. app\\migrations\\M101129185401CreateUserTable).");
    }
    // try mark up
    $migrations = $this->getNewMigrations();
    foreach ($migrations as $i => $migration) {
        if (strpos($migration, $version) === 0) {
            if ($this->confirm("Set migration history at $originalVersion?")) {
                for ($j = 0; $j <= $i; ++$j) {
                    $this->addMigrationHistory($migrations[$j]);
                }
                $this->stdout("The migration history is set at $originalVersion.\nNo actual migration was performed.\n", Console::FG_GREEN);
            }
            return ExitCode::OK;
        }
    }
    // try mark down
    $migrations = array_keys($this->getMigrationHistory(null));
    $migrations[] = static::BASE_MIGRATION;
    foreach ($migrations as $i => $migration) {
        if (strpos($migration, $version) === 0) {
            if ($i === 0) {
                $this->stdout("Already at '$originalVersion'. Nothing needs to be done.\n", Console::FG_YELLOW);
            } elseif ($this->confirm("Set migration history at $originalVersion?")) {
                for ($j = 0; $j < $i; ++$j) {
                    $this->removeMigrationHistory($migrations[$j]);
                }
                $this->stdout("The migration history is set at $originalVersion.\nNo actual migration was performed.\n", Console::FG_GREEN);
            }
            return ExitCode::OK;
        }
    }
    throw new Exception("Unable to find the version '$originalVersion'.");
}

            
actionNew() 公共方法

顯示未套用的新遷移。

此命令將顯示尚未套用的新遷移。例如,

yii migrate/new     # showing the first 10 new migrations
yii migrate/new 5   # showing the first 5 new migrations
yii migrate/new all # showing all new migrations
public void actionNew ( $limit 10 )
$limit integer|string

要顯示的最大新遷移數量。如果它是 all,將顯示所有可用的新遷移。

拋出 yii\console\Exception

如果傳遞了無效的限制值

                public function actionNew($limit = 10)
{
    if ($limit !== 'all') {
        $limit = (int) $limit;
        if ($limit < 1) {
            throw new Exception('The limit must be greater than 0.');
        }
    }
    $migrations = $this->getNewMigrations();
    if (empty($migrations)) {
        $this->stdout("No new migrations found. Your system is up-to-date.\n", Console::FG_GREEN);
    } else {
        $n = count($migrations);
        if ($limit !== 'all' && $n > $limit) {
            $migrations = array_slice($migrations, 0, $limit);
            $this->stdout("Showing $limit out of $n new " . ($n === 1 ? 'migration' : 'migrations') . ":\n", Console::FG_YELLOW);
        } else {
            $this->stdout("Found $n new " . ($n === 1 ? 'migration' : 'migrations') . ":\n", Console::FG_YELLOW);
        }
        foreach ($migrations as $migration) {
            $this->stdout("\t" . $migration . "\n");
        }
    }
    return ExitCode::OK;
}

            
actionRedo() public method

重做最後幾次遷移。

此命令會先還原指定的遷移,然後再次套用它們。例如,

yii migrate/redo     # redo the last applied migration
yii migrate/redo 3   # redo the last 3 applied migrations
yii migrate/redo all # redo all migrations
public integer actionRedo ( $limit 1 )
$limit integer|string

要重做的遷移數量。預設值為 1,表示將重做最後套用的遷移。當等於 "all" 時,將重做所有遷移。

返回 integer

動作執行的狀態。0 表示正常,其他值表示異常。

拋出 yii\console\Exception

如果指定的步驟數小於 1。

                public function actionRedo($limit = 1)
{
    if ($limit === 'all') {
        $limit = null;
    } else {
        $limit = (int) $limit;
        if ($limit < 1) {
            throw new Exception('The step argument must be greater than 0.');
        }
    }
    $migrations = $this->getMigrationHistory($limit);
    if (empty($migrations)) {
        $this->stdout("No migration has been done before.\n", Console::FG_YELLOW);
        return ExitCode::OK;
    }
    $migrations = array_keys($migrations);
    $n = count($migrations);
    $this->stdout("Total $n " . ($n === 1 ? 'migration' : 'migrations') . " to be redone:\n", Console::FG_YELLOW);
    foreach ($migrations as $migration) {
        $this->stdout("\t$migration\n");
    }
    $this->stdout("\n");
    if ($this->confirm('Redo the above ' . ($n === 1 ? 'migration' : 'migrations') . '?')) {
        foreach ($migrations as $migration) {
            if (!$this->migrateDown($migration)) {
                $this->stdout("\nMigration failed. The rest of the migrations are canceled.\n", Console::FG_RED);
                return ExitCode::UNSPECIFIED_ERROR;
            }
        }
        foreach (array_reverse($migrations) as $migration) {
            if (!$this->migrateUp($migration)) {
                $this->stdout("\nMigration failed. The rest of the migrations are canceled.\n", Console::FG_RED);
                return ExitCode::UNSPECIFIED_ERROR;
            }
        }
        $this->stdout("\n$n " . ($n === 1 ? 'migration was' : 'migrations were') . " redone.\n", Console::FG_GREEN);
        $this->stdout("\nMigration redone successfully.\n", Console::FG_GREEN);
    }
    return ExitCode::OK;
}

            
actionTo() public method

升級或降級到指定的版本。

也可以透過提供 UNIX 時間戳記或 strtotime() 函數可解析的字串,將版本降級到過去的特定套用時間。這表示所有在指定的特定時間之後套用的版本都將被還原。

此命令會先還原指定的遷移,然後再次套用它們。例如,

yii migrate/to 101129_185401                          # using timestamp
yii migrate/to m101129_185401_create_user_table       # using full name
yii migrate/to 1392853618                             # using UNIX timestamp
yii migrate/to "2014-02-15 13:00:50"                  # using strtotime() parseable string
yii migrate/to app\migrations\M101129185401CreateUser # using full namespace name
public void actionTo ( $version )
$version string

版本名稱或是應用程式應遷移到的過去特定時間值。這可以是時間戳記、遷移的完整名稱、UNIX 時間戳記,或是可解析的日期時間字串。

拋出 yii\console\Exception

如果版本引數無效。

                public function actionTo($version)
{
    if (($namespaceVersion = $this->extractNamespaceMigrationVersion($version)) !== false) {
        return $this->migrateToVersion($namespaceVersion);
    } elseif (($migrationName = $this->extractMigrationVersion($version)) !== false) {
        return $this->migrateToVersion($migrationName);
    } elseif ((string) (int) $version == $version) {
        return $this->migrateToTime($version);
    } elseif (($time = strtotime($version)) !== false) {
        return $this->migrateToTime($time);
    } else {
        throw new Exception("The version argument must be either a timestamp (e.g. 101129_185401),\n the full name of a migration (e.g. m101129_185401_create_user_table),\n the full namespaced name of a migration (e.g. app\\migrations\\M101129185401CreateUserTable),\n a UNIX timestamp (e.g. 1392853000), or a datetime string parseable\nby the strtotime() function (e.g. 2014-02-15 13:00:50).");
    }
}

            
actionUp() public method

透過套用新遷移來升級應用程式。

例如,

yii migrate     # apply all new migrations
yii migrate 3   # apply the first 3 new migrations
public integer actionUp ( $limit 0 )
$limit integer

要套用的新遷移數量。如果為 0,表示套用所有可用的新遷移。

返回 integer

動作執行的狀態。0 表示正常,其他值表示異常。

                public function actionUp($limit = 0)
{
    $migrations = $this->getNewMigrations();
    if (empty($migrations)) {
        $this->stdout("No new migrations found. Your system is up-to-date.\n", Console::FG_GREEN);
        return ExitCode::OK;
    }
    $total = count($migrations);
    $limit = (int) $limit;
    if ($limit > 0) {
        $migrations = array_slice($migrations, 0, $limit);
    }
    $n = count($migrations);
    if ($n === $total) {
        $this->stdout("Total $n new " . ($n === 1 ? 'migration' : 'migrations') . " to be applied:\n", Console::FG_YELLOW);
    } else {
        $this->stdout("Total $n out of $total new " . ($total === 1 ? 'migration' : 'migrations') . " to be applied:\n", Console::FG_YELLOW);
    }
    foreach ($migrations as $migration) {
        $nameLimit = $this->getMigrationNameLimit();
        if ($nameLimit !== null && strlen($migration) > $nameLimit) {
            $this->stdout("\nThe migration name '$migration' is too long. Its not possible to apply this migration.\n", Console::FG_RED);
            return ExitCode::UNSPECIFIED_ERROR;
        }
        $this->stdout("\t$migration\n");
    }
    $this->stdout("\n");
    $applied = 0;
    if ($this->confirm('Apply the above ' . ($n === 1 ? 'migration' : 'migrations') . '?')) {
        foreach ($migrations as $migration) {
            if (!$this->migrateUp($migration)) {
                $this->stdout("\n$applied from $n " . ($applied === 1 ? 'migration was' : 'migrations were') . " applied.\n", Console::FG_RED);
                $this->stdout("\nMigration failed. The rest of the migrations are canceled.\n", Console::FG_RED);
                return ExitCode::UNSPECIFIED_ERROR;
            }
            $applied++;
        }
        $this->stdout("\n$n " . ($n === 1 ? 'migration was' : 'migrations were') . " applied.\n", Console::FG_GREEN);
        $this->stdout("\nMigrated up successfully.\n", Console::FG_GREEN);
    }
    return ExitCode::OK;
}

            
actions() public method

定義於: 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 [];
}

            
addMigrationHistory() protected abstract method

將新的遷移條目添加到歷史紀錄中。

protected abstract void addMigrationHistory ( $version )
$version string

遷移版本名稱。

                abstract protected function addMigrationHistory($version);

            
afterAction() public method

定義於: 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 method

定義於: 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 method

定義於: 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

行為物件

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

            
attachBehaviors() public method

定義於: 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 method

此方法在動作即將執行前(在所有可能的篩選器之後)調用。它檢查 $migrationPath 是否存在。

public boolean beforeAction ( $action )
$action yii\base\Action

要執行的動作。

返回 boolean

動作是否應繼續執行。

拋出 yii\base\InvalidConfigException

如果 migrationPath 中指定的目錄不存在且動作不是 "create"。

                public function beforeAction($action)
{
    if (parent::beforeAction($action)) {
        if (empty($this->migrationNamespaces) && empty($this->migrationPath)) {
            throw new InvalidConfigException('At least one of `migrationPath` or `migrationNamespaces` should be specified.');
        }
        $this->migrationNamespaces = (array) $this->migrationNamespaces;
        foreach ($this->migrationNamespaces as $key => $value) {
            $this->migrationNamespaces[$key] = trim($value, '\\');
        }
        if (is_array($this->migrationPath)) {
            foreach ($this->migrationPath as $i => $path) {
                $this->migrationPath[$i] = Yii::getAlias($path);
            }
        } elseif ($this->migrationPath !== null) {
            $path = Yii::getAlias($this->migrationPath);
            if (!is_dir($path)) {
                if ($action->id !== 'create') {
                    throw new InvalidConfigException("Migration failed. Directory specified in migrationPath doesn't exist: {$this->migrationPath}");
                }
                FileHelper::createDirectory($path);
            }
            $this->migrationPath = $path;
        }
        $version = Yii::getVersion();
        $this->stdout("Yii Migration Tool (based on Yii v{$version})\n\n");
        return true;
    }
    return false;
}

            
behaviors() public method

定義於: 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 method

定義於: yii\console\Controller::bindActionParams()

將參數綁定到動作。

yii\base\Action 開始使用給定的參數執行時,會呼叫此方法。此方法將首先將參數與動作可用的 選項 繫結。然後驗證給定的引數。

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 method (available since version 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 method

定義於: yii\base\Component::canGetProperty()

返回一個值,指示屬性是否可以讀取。

如果屬性可以讀取

  • 類別具有與指定名稱相關聯的 getter 方法 (在這種情況下,屬性名稱不區分大小寫);
  • 類別具有具有指定名稱的成員變數 (當 $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 method

定義於: yii\base\Component::canSetProperty()

返回一個值,指示屬性是否可以設定。

如果屬性可以寫入

  • 類別具有與指定名稱相關聯的 setter 方法 (在這種情況下,屬性名稱不區分大小寫);
  • 類別具有具有指定名稱的成員變數 (當 $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 method
自 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 method

定義於: 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 method

定義於: yii\base\Controller::createAction()

根據給定的動作 ID 建立一個動作。

此方法首先檢查動作 ID 是否已在 actions() 中宣告。如果是,它將使用該處宣告的配置來建立動作物件。如果不是,它將尋找控制器方法,其名稱格式為 actionXyz,其中 xyz 是動作 ID。如果找到,將會建立並回傳代表該方法的 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;
}

            
createMigration() protected method

建立新的遷移實例。

protected yii\db\MigrationInterface createMigration ( $class )
$class string

遷移類別名稱

返回 yii\db\MigrationInterface

遷移實例

                protected function createMigration($class)
{
    $this->includeMigrationFile($class);
    /** @var MigrationInterface $migration */
    $migration = Yii::createObject($class);
    if ($migration instanceof BaseObject && $migration->canSetProperty('compact')) {
        $migration->compact = $this->compact;
    }
    return $migration;
}

            
detachBehavior() public method

定義於: 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 method

定義於: yii\base\Component::detachBehaviors()

從組件分離所有行為。

public void detachBehaviors ( )

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

            
ensureBehaviors() public method

定義於: 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 method

定義於: 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;
}

            
generateMigrationSourceCode() protected method (available since version 2.0.8)

產生新的遷移原始碼 PHP 程式碼。

子類別可以覆寫此方法,為此過程新增額外的邏輯或變化。

protected string generateMigrationSourceCode ( $params )
$params array

產生參數,通常會出現以下參數

  • name: 字串 遷移基礎名稱
  • className: 字串 遷移類別名稱
返回 string

產生的 PHP 程式碼。

                protected function generateMigrationSourceCode($params)
{
    return $this->renderFile(Yii::getAlias($this->templateFile), $params);
}

            
getActionArgsHelp() public method

定義於: yii\console\Controller::getActionArgsHelp()

返回動作的匿名參數的說明資訊。

回傳值應該是一個陣列。鍵是引數名稱,值是對應的說明資訊。每個值都必須是具有以下結構的陣列

  • required: 布林值,此引數是否為必要項
  • type: 字串|null,此引數的 PHP 類型
  • default: 混合類型,此引數的預設值
  • comment: 字串,此引數的描述

預設實作將回傳從與動作方法對應的參數的 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 method

定義於: 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 method

定義於: yii\console\Controller::getActionHelpSummary()

返回描述指定動作的單行簡短摘要。

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

要取得摘要的動作

返回 string

描述指定動作的單行簡短摘要。

                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 method
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 method

定義於: yii\console\Controller::getActionOptionsHelp()

返回動作選項的說明資訊。

傳回值應為陣列。鍵名為選項名稱,值為對應的說明資訊。每個值都必須是以下結構的陣列

  • type: 字串,此參數的 PHP 型別。
  • default: 字串,此參數的預設值
  • 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;
}

            
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()

返回描述此控制器的單行簡短摘要。

您可以覆寫此方法以傳回自訂的摘要。預設實作會從 PHPDoc 註解中傳回第一行。

public string getHelpSummary ( )

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

            
getMigrationHistory() protected abstract 方法

返回遷移歷史紀錄。

protected abstract array getMigrationHistory ( $limit )
$limit integer|null

要傳回的歷史記錄中的最大記錄數。null 表示「無限制」。

返回 array

遷移歷史記錄

                abstract protected function getMigrationHistory($limit);

            
getMigrationNameLimit() protected 方法 (自版本 2.0.13 起可用)

返回遷移的最大名稱長度。

子類別可以覆寫此方法以定義限制。

protected integer|null getMigrationNameLimit ( )
返回 integer|null

遷移的最大名稱長度,如果沒有限制則為 null

                protected function getMigrationNameLimit()
{
    return null;
}

            
getModules() public 方法

定義於: yii\base\Controller::getModules()

返回此控制器的所有祖先模組。

陣列中的第一個模組是最外層的模組 (即應用程式實例),而最後一個是最內層的模組。

public yii\base\Module[] getModules ( )
返回 yii\base\Module[]

此控制器所在的所有上層模組 (ancestor modules)。

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

            
getNewMigrations() protected 方法

返回未套用的遷移。

protected array getNewMigrations ( )
返回 array

新遷移列表

                protected function getNewMigrations()
{
    $applied = [];
    foreach ($this->getMigrationHistory(null) as $class => $time) {
        $applied[trim($class, '\\')] = true;
    }
    $migrationPaths = [];
    if (is_array($this->migrationPath)) {
        foreach ($this->migrationPath as $path) {
            $migrationPaths[] = [$path, ''];
        }
    } elseif (!empty($this->migrationPath)) {
        $migrationPaths[] = [$this->migrationPath, ''];
    }
    foreach ($this->migrationNamespaces as $namespace) {
        $migrationPaths[] = [$this->getNamespacePath($namespace), $namespace];
    }
    $migrations = [];
    foreach ($migrationPaths as $item) {
        list($migrationPath, $namespace) = $item;
        if (!file_exists($migrationPath)) {
            continue;
        }
        $handle = opendir($migrationPath);
        while (($file = readdir($handle)) !== false) {
            if ($file === '.' || $file === '..') {
                continue;
            }
            $path = $migrationPath . DIRECTORY_SEPARATOR . $file;
            if (preg_match('/^(m(\d{6}_?\d{6})\D.*?)\.php$/is', $file, $matches) && is_file($path)) {
                $class = $matches[1];
                if (!empty($namespace)) {
                    $class = $namespace . '\\' . $class;
                }
                $time = str_replace('_', '', $matches[2]);
                if (!isset($applied[$class])) {
                    $migrations[$time . '\\' . $class] = $class;
                }
            }
        }
        closedir($handle);
    }
    ksort($migrations);
    return array_values($migrations);
}

            
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

目前請求的路由 (module ID、controller ID 和 action 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 物件來實作實際的 view 呈現。如果未設定,則預設為「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 目錄下,名為 controller $id 的目錄。

public string getViewPath ( )
返回 string

包含此控制器視圖檔案的目錄。

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

            
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()

返回一個值,指示是否為此組件定義了屬性。

如果符合以下條件,則定義了屬性

  • 類別具有與指定名稱關聯的 getter 或 setter 方法 (在這種情況下,屬性名稱不區分大小寫);
  • 類別具有具有指定名稱的成員變數 (當 $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);
}

            
includeMigrationFile() protected 方法 (自版本 2.0.12 起可用)

包含給定遷移類別名稱的遷移檔案。

此函數對於命名空間遷移不會執行任何操作,這些遷移會由自動載入自動載入。它將包含遷移檔案,方法是在 $migrationPath 中搜尋沒有命名空間的類別。

protected void includeMigrationFile ( $class )
$class string

遷移類別名稱。

                protected function includeMigrationFile($class)
{
    $class = trim($class, '\\');
    if (strpos($class, '\\') === false) {
        if (is_array($this->migrationPath)) {
            foreach ($this->migrationPath as $path) {
                $file = $path . DIRECTORY_SEPARATOR . $class . '.php';
                if (is_file($file)) {
                    require_once $file;
                    break;
                }
            }
        } else {
            $file = $this->migrationPath . DIRECTORY_SEPARATOR . $class . '.php';
            require_once $file;
        }
    }
}

            
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());
}

            
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;
}

            
migrateDown() protected 方法

使用指定的遷移類別降級。

protected boolean migrateDown ( $class )
$class string

遷移類別名稱

返回 boolean

遷移是否成功

                protected function migrateDown($class)
{
    if ($class === self::BASE_MIGRATION) {
        return true;
    }
    $this->stdout("*** reverting $class\n", Console::FG_YELLOW);
    $start = microtime(true);
    $migration = $this->createMigration($class);
    if ($migration->down() !== false) {
        $this->removeMigrationHistory($class);
        $time = microtime(true) - $start;
        $this->stdout("*** reverted $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_GREEN);
        return true;
    }
    $time = microtime(true) - $start;
    $this->stdout("*** failed to revert $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_RED);
    return false;
}

            
migrateToTime() protected 方法

遷移到過去指定的套用時間。

protected void migrateToTime ( $time )
$time integer

UNIX 時間戳記值。

                protected function migrateToTime($time)
{
    $count = 0;
    $migrations = array_values($this->getMigrationHistory(null));
    while ($count < count($migrations) && $migrations[$count] > $time) {
        ++$count;
    }
    if ($count === 0) {
        $this->stdout("Nothing needs to be done.\n", Console::FG_GREEN);
    } else {
        return $this->actionDown($count);
    }
    return ExitCode::OK;
}

            
migrateToVersion() protected 方法

遷移到特定版本。

protected integer migrateToVersion ( $version )
$version string

完整格式的名稱。

返回 integer

CLI 退出代碼

拋出 yii\console\Exception

如果找不到提供的版本。

                protected function migrateToVersion($version)
{
    $originalVersion = $version;
    // try migrate up
    $migrations = $this->getNewMigrations();
    foreach ($migrations as $i => $migration) {
        if (strpos($migration, $version) === 0) {
            return $this->actionUp($i + 1);
        }
    }
    // try migrate down
    $migrations = array_keys($this->getMigrationHistory(null));
    foreach ($migrations as $i => $migration) {
        if (strpos($migration, $version) === 0) {
            if ($i === 0) {
                $this->stdout("Already at '$originalVersion'. Nothing needs to be done.\n", Console::FG_YELLOW);
            } else {
                return $this->actionDown($i);
            }
            return ExitCode::OK;
        }
    }
    throw new Exception("Unable to find the version '$originalVersion'.");
}

            
migrateUp() protected 方法

使用指定的遷移類別升級。

protected boolean migrateUp ( $class )
$class string

遷移類別名稱

返回 boolean

遷移是否成功

                protected function migrateUp($class)
{
    if ($class === self::BASE_MIGRATION) {
        return true;
    }
    $this->stdout("*** applying $class\n", Console::FG_YELLOW);
    $start = microtime(true);
    $migration = $this->createMigration($class);
    if ($migration->up() !== false) {
        $this->addMigrationHistory($class);
        $time = microtime(true) - $start;
        $this->stdout("*** applied $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_GREEN);
        return true;
    }
    $time = microtime(true) - $start;
    $this->stdout("*** failed to apply $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_RED);
    return false;
}

            
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)

其中 $eventyii\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 可呼叫

事件處理常式

$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 起可用)

定義於: yii\console\Controller::optionAliases()

返回選項別名。

子類別可以覆寫此方法以指定別名選項。

另請參閱 options()

public array optionAliases ( )
返回 array

適用於動作的選項別名名稱,其中鍵是選項的別名,值是選項名稱。

                public function optionAliases()
{
    return [
        'h' => 'help',
    ];
}

            
options() public 方法

返回動作 (id) 的有效選項名稱。選項需要存在一個公共成員變數,其名稱為選項名稱。

子類別可以覆寫此方法以指定可能的選項。

請注意,透過選項設定的值在呼叫 beforeAction() 之前不可用。

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

目前請求的動作 ID

返回 string[]

適用於動作的選項名稱

                public function options($actionID)
{
    return array_merge(
        parent::options($actionID),
        ['migrationPath', 'migrationNamespaces', 'compact'], // global for all actions
        $actionID === 'create' ? ['templateFile'] : [] // action create
    );
}

            
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 method

定義於: yii\console\Controller::prompt()

提示使用者輸入並驗證它。

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

提示字串

$options array

驗證輸入的選項

  • required: 是否為必填
  • default: 若使用者未輸入任何內容時的預設值
  • pattern: 驗證使用者輸入的正規表示式
  • validator: 用於驗證輸入的可呼叫函式。該函式必須接受兩個參數
    • $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'] : '';
}

            
removeMigrationHistory() protected abstract method

從歷史紀錄中移除現有的遷移。

protected abstract void removeMigrationHistory ( $version )
$version string

遷移版本名稱。

                abstract protected function removeMigrationHistory($version);

            
render() public method

定義於: yii\base\Controller::render()

渲染視圖並在可用時套用佈局。

要呈現的視圖可以使用以下格式之一指定

  • 路徑別名 (例如 "@app/views/site/index");
  • 應用程式內的絕對路徑 (例如 "//site/index"):視圖名稱以雙斜線開頭。實際的視圖檔案將在應用程式的 視圖路徑 下尋找。
  • 模組內的絕對路徑 (例如 "/site/index"):視圖名稱以單斜線開頭。實際的視圖檔案將在 視圖路徑 of $module 下尋找。
  • 相對路徑 (例如 "index"):實際的視圖檔案將在 $viewPath 下尋找。

要決定應套用哪個版面配置,將執行以下兩個步驟

  1. 在第一步中,它會決定版面配置名稱和上下文模組
  • 如果 $layout 指定為字串,則使用它作為版面配置名稱,並使用 $module 作為上下文模組;
  • 如果 $layout 為 null,則搜尋此控制器所有祖先模組,並找到第一個 layout 不為 null 的模組。版面配置和相應的模組將分別用作版面配置名稱和上下文模組。如果找不到這樣的模組或相應的版面配置不是字串,它將傳回 false,表示沒有適用的版面配置。
  1. 在第二步中,它根據先前找到的版面配置名稱和上下文模組來決定實際的版面配置檔案。版面配置名稱可以是
  • 路徑別名 (例如 "@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 method (available since version 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 method

定義於: 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 method

定義於: 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 method

定義於: 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 method

定義於: 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 method

定義於: 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 method

定義於: yii\base\Controller::setView()

設定此控制器要使用的視圖物件。

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

可用於渲染視圖或視圖檔案的視圖物件。

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

            
setViewPath() public method (available since version 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 method

定義於: yii\console\Controller::stderr()

將字串印到 STDERR。

您可以選擇性地使用 ANSI 代碼格式化字串,方法是使用 yii\helpers\Console 中定義的常數傳遞額外參數。

範例

$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 method

定義於: yii\console\Controller::stdout()

將字串印到 STDOUT。

您可以選擇性地使用 ANSI 代碼格式化字串,方法是使用 yii\helpers\Console 中定義的常數傳遞額外參數。

範例

$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 method

定義於: 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);
}

            
truncateDatabase() protected method (available since version 2.0.13)

截斷資料庫。

應在子類別中覆寫此方法,以實作清除資料庫的任務。

protected void truncateDatabase ( )
拋出 yii\base\NotSupportedException

如果未覆寫

                protected function truncateDatabase()
{
    throw new NotSupportedException('This command is not implemented in ' . get_class($this));
}