類別 yii\base\DynamicModel
DynamicModel 是一個模型類別,支援在運行時定義屬性(所謂的「動態屬性」),可使用其建構子或 defineAttribute()。 DynamicModel 可用於支援特設的資料驗證。
DynamicModel 的典型用法如下:
public function actionSearch($name, $email)
{
$model = DynamicModel::validateData(compact('name', 'email'), [
[['name', 'email'], 'string', 'max' => 128],
['email', 'email'],
]);
if ($model->hasErrors()) {
// validation fails
} else {
// validation succeeds
}
}
以上範例示範如何藉助 DynamicModel 驗證 $name
和 $email
。validateData() 方法會建立 DynamicModel 的實例,使用給定的資料(本例中為 name
和 email
)定義屬性,然後呼叫 yii\base\Model::validate()。
您可以使用 hasErrors() 檢查驗證結果,就像使用一般模型一樣。您也可以透過模型實例存取定義的動態屬性,例如 $model->name
和 $model->email
。
或者,您可以使用以下更「傳統」的語法來執行特設的資料驗證
$model = new DynamicModel(compact('name', 'email'));
$model->addRule(['name', 'email'], 'string', ['max' => 128])
->addRule('email', 'email')
->validate();
公共屬性
屬性 | 類型 | 描述 | 定義於 |
---|---|---|---|
$activeValidators | yii\validators\Validator[] | 適用於目前 $scenario 的驗證器。 | yii\base\Model |
$attributes | 陣列 | 屬性值 (名稱 => 值)。 | yii\base\Model |
$behaviors | yii\base\Behavior[] | 附加到此元件的行為列表。 | yii\base\Component |
$errors | 陣列 | 所有屬性或指定屬性的錯誤。 | yii\base\Model |
$firstErrors | 陣列 | 第一個錯誤。 | yii\base\Model |
$iterator | ArrayIterator | 用於遍歷列表中項目的迭代器。 | yii\base\Model |
$scenario | 字串 | 此模型所處的情境。 | yii\base\Model |
$validators | ArrayObject|yii\validators\Validator[] | 模型中宣告的所有驗證器。 | yii\base\Model |
公共方法
受保護方法
方法 | 描述 | 定義於 |
---|---|---|
extractFieldsFor() | 從欄位集合中,為給定的根欄位擷取巢狀欄位。巢狀欄位以點 (.) 分隔。例如:「item.id」。先前的範例會擷取「id」。 | yii\base\ArrayableTrait |
extractRootFields() | 從巢狀欄位中擷取根欄位名稱。 | yii\base\ArrayableTrait |
resolveFields() | 判斷哪些欄位可由 toArray() 傳回。 | yii\base\ArrayableTrait |
事件
事件 | 類型 | 描述 | 定義於 |
---|---|---|---|
EVENT_AFTER_VALIDATE | yii\base\Event | 在 validate() 結束時引發的事件 | yii\base\Model |
EVENT_BEFORE_VALIDATE | yii\base\ModelEvent | 在 validate() 開始時引發的事件。 | yii\base\Model |
方法詳情
定義於: yii\base\Component::__call()
呼叫未作為類別方法的具名方法。
此方法將檢查是否有任何附加的行為具有具名方法,並在可用時執行它。
請勿直接呼叫此方法,因為它是 PHP 魔術方法,會在調用未知方法時隱式呼叫。
public mixed __call ( $name, $params ) | ||
$name | 字串 |
方法名稱 |
$params | 陣列 |
方法參數 |
return | mixed |
方法傳回值 |
---|---|---|
throws | 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()");
}
public void __clone ( ) |
public function __clone()
{
parent::__clone();
$this->_errors = null;
$this->_validators = null;
}
建構子。
public void __construct ( array $attributes = [], $config = [] ) | ||
$attributes | 陣列 |
正在定義的屬性(名稱-值組或名稱)。 |
$config | 陣列 |
要套用至此物件的組態陣列。 |
public function __construct(array $attributes = [], $config = [])
{
foreach ($attributes as $name => $value) {
if (is_int($name)) {
$this->_attributes[$value] = null;
} else {
$this->_attributes[$name] = $value;
}
}
parent::__construct($config);
}
傳回元件屬性的值。
此方法將依以下順序檢查並採取相應措施
- getter 定義的屬性:傳回 getter 結果
- 行為的屬性:傳回行為屬性值
請勿直接呼叫此方法,因為它是 PHP 魔術方法,會在執行 $value = $component->property;
時隱式呼叫。
public mixed __get ( $name ) | ||
$name | 字串 |
屬性名稱 |
return | mixed |
屬性值或行為屬性的值 |
---|---|---|
throws | yii\base\UnknownPropertyException |
如果未定義屬性 |
throws | yii\base\InvalidCallException |
如果屬性為唯寫。 |
public function __get($name)
{
if ($this->hasAttribute($name)) {
return $this->_attributes[$name];
}
return parent::__get($name);
}
檢查屬性是否已設定,即已定義且非 null。
此方法將依以下順序檢查並採取相應措施
- setter 定義的屬性:傳回屬性是否已設定
- 行為的屬性:傳回屬性是否已設定
- 對於不存在的屬性,傳回
false
請勿直接呼叫此方法,因為它是 PHP 魔術方法,會在執行 isset($component->property)
時隱式呼叫。
public boolean __isset ( $name ) | ||
$name | 字串 |
屬性名稱或事件名稱 |
return | boolean |
具名屬性是否已設定 |
---|
public function __isset($name)
{
if ($this->hasAttribute($name)) {
return isset($this->_attributes[$name]);
}
return parent::__isset($name);
}
設定元件屬性的值。
此方法將依以下順序檢查並採取相應措施
- setter 定義的屬性:設定屬性值
- 格式為「on xyz」的事件:將處理常式附加到事件「xyz」
- 格式為「as xyz」的行為:附加名為「xyz」的行為
- 行為的屬性:設定行為屬性值
請勿直接呼叫此方法,因為它是 PHP 魔術方法,會在執行 $component->property = $value;
時隱式呼叫。
public void __set ( $name, $value ) | ||
$name | 字串 |
屬性名稱或事件名稱 |
$value | mixed |
屬性值 |
throws | yii\base\UnknownPropertyException |
如果未定義屬性 |
---|---|---|
throws | yii\base\InvalidCallException |
如果屬性為唯讀。 |
public function __set($name, $value)
{
if ($this->hasAttribute($name)) {
$this->_attributes[$name] = $value;
} else {
parent::__set($name, $value);
}
}
將元件屬性設定為 null。
此方法將依以下順序檢查並採取相應措施
- setter 定義的屬性:將屬性值設定為 null
- 行為的屬性:將屬性值設定為 null
請勿直接呼叫此方法,因為它是 PHP 魔術方法,會在執行 unset($component->property)
時隱式呼叫。
public void __unset ( $name ) | ||
$name | 字串 |
屬性名稱 |
throws | yii\base\InvalidCallException |
如果屬性為唯讀。 |
---|
public function __unset($name)
{
if ($this->hasAttribute($name)) {
unset($this->_attributes[$name]);
} else {
parent::__unset($name);
}
}
定義於: yii\base\Model::activeAttributes()
傳回目前情境中要進行驗證的屬性名稱。
public string[] activeAttributes ( ) | ||
return | 字串[] |
安全屬性名稱 |
---|
public function activeAttributes()
{
$scenario = $this->getScenario();
$scenarios = $this->scenarios();
if (!isset($scenarios[$scenario])) {
return [];
}
$attributes = array_keys(array_flip($scenarios[$scenario]));
foreach ($attributes as $i => $attribute) {
if (strncmp($attribute, '!', 1) === 0) {
$attributes[$i] = substr($attribute, 1);
}
}
return $attributes;
}
定義於: yii\base\Model::addError()
將新錯誤新增至指定的屬性。
public void addError ( $attribute, $error = '' ) | ||
$attribute | 字串 |
屬性名稱 |
$error | 字串 |
新的錯誤訊息 |
public function addError($attribute, $error = '')
{
$this->_errors[$attribute][] = $error;
}
定義於: yii\base\Model::addErrors()
新增錯誤列表。
public void addErrors ( array $items ) | ||
$items | 陣列 |
錯誤列表。陣列鍵必須是屬性名稱。陣列值應為錯誤訊息。如果屬性有多個錯誤,則這些錯誤必須以陣列形式給出。您可以將 getErrors() 的結果用作此參數的值。 |
public function addErrors(array $items)
{
foreach ($items as $attribute => $errors) {
if (is_array($errors)) {
foreach ($errors as $error) {
$this->addError($attribute, $error);
}
} else {
$this->addError($attribute, $errors);
}
}
}
將驗證規則新增至此模型。
您也可以直接操作 $validators 以新增或移除驗證規則。此方法提供了一個捷徑。
public $this addRule ( $attributes, $validator, $options = [] ) | ||
$attributes | string|array |
規則要驗證的屬性。 |
$validator | string|yii\validators\Validator|Closure |
驗證器。這可以是下列其中之一
|
$options | 陣列 |
要套用至驗證器的選項(名稱-值組)。 |
public function addRule($attributes, $validator, $options = [])
{
$validators = $this->getValidators();
if ($validator instanceof Validator) {
$validator->attributes = (array)$attributes;
} else {
$validator = Validator::createValidator($validator, $this, (array)$attributes, $options);
}
$validators->append($validator);
$this->defineAttributesByValidator($validator);
return $this;
}
定義於: yii\base\Model::afterValidate()
此方法在驗證結束後調用。
預設實作會引發 afterValidate
事件。您可以覆寫此方法,在驗證後執行後處理。請確保調用父實作,以便可以引發事件。
public void afterValidate ( ) |
public function afterValidate()
{
$this->trigger(self::EVENT_AFTER_VALIDATE);
}
定義於: yii\base\Component::attachBehavior()
將行為附加到此元件。
此方法將根據給定的組態建立行為物件。之後,將透過呼叫 yii\base\Behavior::attach() 方法將行為物件附加到此元件。
另請參閱 detachBehavior()。
public yii\base\Behavior attachBehavior ( $name, $behavior ) | ||
$name | 字串 |
行為的名稱。 |
$behavior | string|array|yii\base\Behavior |
行為組態。這可以是下列其中之一
|
return | yii\base\Behavior |
行為物件 |
---|
public function attachBehavior($name, $behavior)
{
$this->ensureBehaviors();
return $this->attachBehaviorInternal($name, $behavior);
}
定義於: yii\base\Component::attachBehaviors()
將行為列表附加到此元件。
每個行為都依其名稱編製索引,並且應該是 yii\base\Behavior 物件、指定行為類別的字串,或是用於建立行為的組態陣列。
另請參閱 attachBehavior()。
public void attachBehaviors ( $behaviors ) | ||
$behaviors | 陣列 |
要附加到元件的行為列表 |
public function attachBehaviors($behaviors)
{
$this->ensureBehaviors();
foreach ($behaviors as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
定義於: yii\base\Model::attributeHints()
傳回屬性提示。
屬性提示主要用於顯示目的。例如,給定屬性 isPublic
,我們可以宣告提示 Whether the post should be visible for not logged in users
,這提供屬性意義的使用者友善描述,並且可以顯示給終端使用者。
與標籤不同,如果省略其明確宣告,則不會產生提示。
請注意,為了繼承父類別中定義的提示,子類別需要使用諸如 array_merge()
之類的函式將父提示與子提示合併。
public array attributeHints ( ) | ||
return | 陣列 |
屬性提示 (名稱 => 提示) |
---|
public function attributeHints()
{
return [];
}
傳回屬性標籤。
屬性標籤主要用於顯示目的。例如,給定屬性 firstName
,我們可以宣告標籤 First Name
,這更使用者友善,並且可以顯示給終端使用者。
預設情況下,屬性標籤是使用 generateAttributeLabel() 產生的。此方法可讓您明確指定屬性標籤。
請注意,為了繼承父類別中定義的標籤,子類別需要使用諸如 array_merge()
之類的函式將父標籤與子標籤合併。
public array attributeLabels ( ) | ||
return | 陣列 |
屬性標籤 (name => label) |
---|
public function attributeLabels()
{
return $this->_attributeLabels;
}
傳回屬性名稱列表。
預設情況下,此方法會回傳類別中所有公開且非靜態的屬性。您可以覆寫此方法來變更預設行為。
public string[] attributes ( ) | ||
return | 字串[] |
屬性名稱列表。 |
---|
public function attributes()
{
return array_keys($this->_attributes);
}
定義於: yii\base\Model::beforeValidate()
此方法在驗證開始前調用。
預設實作會觸發 beforeValidate
事件。您可以覆寫此方法,在驗證前執行初步檢查。請確保調用父類別的實作,以便可以觸發事件。
public boolean beforeValidate ( ) | ||
return | boolean |
是否應執行驗證。預設值為 true。如果回傳 false,驗證將停止,且模型將被視為無效。 |
---|
public function beforeValidate()
{
$event = new ModelEvent();
$this->trigger(self::EVENT_BEFORE_VALIDATE, $event);
return $event->isValid;
}
定義於: yii\base\Component::behaviors()
傳回此元件應作為的行為列表。
子類別可以覆寫此方法,以指定它們想要表現為的行為。
此方法的回傳值應為行為物件或組態的陣列,並以行為名稱作為索引。行為組態可以是指定行為類別的字串,或是具有以下結構的陣列
'behaviorName' => [
'class' => 'BehaviorClass',
'property1' => 'value1',
'property2' => 'value2',
]
請注意,行為類別必須繼承自 yii\base\Behavior。行為可以使用名稱或匿名方式附加。當使用名稱作為陣列鍵時,可以使用此名稱稍後透過 getBehavior() 檢索行為,或透過 detachBehavior() 分離行為。匿名行為無法檢索或分離。
在此方法中宣告的行為將自動 (依需求) 附加到組件。
public array behaviors ( ) | ||
return | 陣列 |
行為組態。 |
---|
public function behaviors()
{
return [];
}
傳回值,指出是否可以讀取屬性。
如果符合以下任一條件,則可以讀取屬性
- 類別具有與指定名稱相關聯的 getter 方法 (在這種情況下,屬性名稱不區分大小寫);
- 類別具有具有指定名稱的成員變數 (當
$checkVars
為 true 時); - 附加的行為具有給定名稱的可讀屬性 (當
$checkBehaviors
為 true 時)。
public boolean canGetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | 字串 |
屬性名稱 |
$checkVars | boolean |
是否將成員變數視為屬性 |
$checkBehaviors | boolean |
是否將行為的屬性視為此組件的屬性 |
return | boolean |
屬性是否可讀 |
---|
public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
{
return parent::canGetProperty($name, $checkVars, $checkBehaviors) || $this->hasAttribute($name);
}
傳回值,指出是否可以設定屬性。
如果符合以下任一條件,則可以寫入屬性
- 類別具有與指定名稱相關聯的 setter 方法 (在這種情況下,屬性名稱不區分大小寫);
- 類別具有具有指定名稱的成員變數 (當
$checkVars
為 true 時); - 附加的行為具有給定名稱的可寫屬性 (當
$checkBehaviors
為 true 時)。
public boolean canSetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | 字串 |
屬性名稱 |
$checkVars | boolean |
是否將成員變數視為屬性 |
$checkBehaviors | boolean |
是否將行為的屬性視為此組件的屬性 |
return | boolean |
屬性是否可寫入 |
---|
public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
{
return parent::canSetProperty($name, $checkVars, $checkBehaviors) || $this->hasAttribute($name);
}
::class
。
定義於: yii\base\BaseObject::className()
傳回此類別的完整限定名稱。
public static string className ( ) | ||
return | 字串 |
此類別的完整限定名稱。 |
---|
public static function className()
{
return get_called_class();
}
定義於: yii\base\Model::clearErrors()
移除所有屬性或單一屬性的錯誤。
public void clearErrors ( $attribute = null ) | ||
$attribute | string|null |
屬性名稱。使用 null 移除所有屬性的錯誤。 |
public function clearErrors($attribute = null)
{
if ($attribute === null) {
$this->_errors = [];
} else {
unset($this->_errors[$attribute]);
}
}
定義於: yii\base\Model::createValidators()
根據 rules() 中指定的驗證規則,建立驗證器物件。
與 getValidators() 不同,每次調用此方法時,都會回傳新的驗證器列表。
public ArrayObject createValidators ( ) | ||
return | ArrayObject |
驗證器 |
---|---|---|
throws | yii\base\InvalidConfigException |
如果任何驗證規則組態無效 |
public function createValidators()
{
$validators = new ArrayObject();
foreach ($this->rules() as $rule) {
if ($rule instanceof Validator) {
$validators->append($rule);
} elseif (is_array($rule) && isset($rule[0], $rule[1])) { // attributes, validator type
$validator = Validator::createValidator($rule[1], $this, (array) $rule[0], array_slice($rule, 2));
$validators->append($validator);
} else {
throw new InvalidConfigException('Invalid validation rule: a rule must specify both attribute names and validator type.');
}
}
return $validators;
}
定義屬性。
public void defineAttribute ( $name, $value = null ) | ||
$name | 字串 |
屬性名稱。 |
$value | mixed |
屬性值。 |
public function defineAttribute($name, $value = null)
{
$this->_attributes[$name] = $value;
}
public yii\base\Behavior|null detachBehavior ( $name ) | ||
$name | 字串 |
行為的名稱。 |
return | 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;
}
定義於: yii\base\Component::detachBehaviors()
從元件分離所有行為。
public void detachBehaviors ( ) |
public function detachBehaviors()
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $name => $behavior) {
$this->detachBehavior($name);
}
}
定義於: 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);
}
}
}
定義於: yii\base\ArrayableTrait::extraFields()
傳回可進一步展開並由 toArray() 傳回的欄位列表。
此方法與 fields() 類似,不同之處在於此方法回傳的欄位列表預設不會由 toArray() 回傳。只有在調用 toArray() 時明確指定要擴展的欄位名稱時,才會匯出它們的值。
預設實作回傳一個空陣列。
您可以覆寫此方法,以根據某些上下文資訊 (例如,當前應用程式使用者) 回傳可擴展欄位的列表。
另請參閱
public array extraFields ( ) | ||
return | 陣列 |
可擴展欄位名稱或欄位定義的列表。請參閱 fields() 以取得回傳值的格式。 |
---|
public function extraFields()
{
return [];
}
定義於: yii\base\ArrayableTrait::extractFieldsFor()
從欄位集合中,為給定的根欄位擷取巢狀欄位。巢狀欄位以點 (.) 分隔。例如:「item.id」。先前的範例會擷取「id」。
protected array extractFieldsFor ( array $fields, $rootField ) | ||
$fields | 陣列 |
請求提取的欄位 |
$rootField | 字串 |
我們要為其提取巢狀欄位的根欄位 |
return | 陣列 |
為給定欄位提取的巢狀欄位 |
---|
protected function extractFieldsFor(array $fields, $rootField)
{
$result = [];
foreach ($fields as $field) {
if (0 === strpos($field, "{$rootField}.")) {
$result[] = preg_replace('/^' . preg_quote($rootField, '/') . '\./i', '', $field);
}
}
return array_unique($result);
}
定義於: yii\base\ArrayableTrait::extractRootFields()
從巢狀欄位中擷取根欄位名稱。
巢狀欄位以點 (.) 分隔。例如:"item.id"。先前的範例將提取 "item"。
protected array extractRootFields ( array $fields ) | ||
$fields | 陣列 |
請求提取的欄位 |
return | 陣列 |
從給定巢狀欄位提取的根欄位 |
---|
protected function extractRootFields(array $fields)
{
$result = [];
foreach ($fields as $field) {
$result[] = current(explode('.', $field, 2));
}
if (in_array('*', $result, true)) {
$result = [];
}
return array_unique($result);
}
定義於: yii\base\ArrayableTrait::fields()
當未指定任何特定欄位時,傳回應由 toArray() 預設傳回的欄位列表。
欄位是由 toArray() 回傳的陣列中的具名元素。
此方法應回傳欄位名稱或欄位定義的陣列。如果是前者,欄位名稱將被視為物件屬性名稱,其值將用作欄位值。如果是後者,陣列鍵應為欄位名稱,而陣列值應為對應的欄位定義,它可以是物件屬性名稱或回傳對應欄位值的 PHP 可調用物件。可調用物件的簽名應為
function ($model, $field) {
// return field value
}
例如,以下程式碼宣告了四個欄位
email
:欄位名稱與屬性名稱email
相同;firstName
和lastName
:欄位名稱為firstName
和lastName
,它們的值從first_name
和last_name
屬性取得;fullName
:欄位名稱為fullName
。其值是透過串聯first_name
和last_name
取得。
return [
'email',
'firstName' => 'first_name',
'lastName' => 'last_name',
'fullName' => function () {
return $this->first_name . ' ' . $this->last_name;
},
];
在此方法中,您可能也希望根據某些上下文資訊回傳不同的欄位列表。例如,根據當前應用程式使用者的權限,您可以回傳不同的可見欄位集或過濾掉某些欄位。
此方法的預設實作回傳以自身索引的公開物件成員變數。
另請參閱 toArray()。
public array fields ( ) | ||
return | 陣列 |
欄位名稱或欄位定義的列表。 |
---|
public function fields()
{
$fields = array_keys(Yii::getObjectVars($this));
return array_combine($fields, $fields);
}
定義於: yii\base\Model::formName()
傳回此模型類別應使用的表單名稱。
表單名稱主要由 yii\widgets\ActiveForm 使用,以確定如何命名模型中屬性的輸入欄位。如果表單名稱為 "A",且屬性名稱為 "b",則對應的輸入名稱將為 "A[b]"。如果表單名稱為空字串,則輸入名稱將為 "b"。
上述命名架構的目的是,對於包含多個不同模型的表單,每個模型的屬性都分組在 POST 資料的子陣列中,這樣更容易區分它們。
預設情況下,此方法會回傳模型類別名稱 (不包含命名空間部分) 作為表單名稱。當模型用於不同的表單時,您可以覆寫它。
另請參閱 load()。
public string formName ( ) | ||
return | 字串 |
此模型類別的表單名稱。 |
---|---|---|
throws | yii\base\InvalidConfigException |
當使用匿名類別定義表單且未覆寫 |
public function formName()
{
$reflector = new ReflectionClass($this);
if (PHP_VERSION_ID >= 70000 && $reflector->isAnonymous()) {
throw new InvalidConfigException('The "formName()" method should be explicitly defined for anonymous models');
}
return $reflector->getShortName();
}
定義於: yii\base\Model::generateAttributeLabel()
根據給定的屬性名稱,產生使用者友善的屬性標籤。
這是透過將底線、破折號和點替換為空格,並將每個單字的第一個字母更改為大寫來完成的。例如,'department_name' 或 'DepartmentName' 將產生 'Department Name'。
public string generateAttributeLabel ( $name ) | ||
$name | 字串 |
欄位名稱 |
return | 字串 |
屬性標籤 |
---|
public function generateAttributeLabel($name)
{
return Inflector::camel2words($name, true);
}
定義於: yii\base\Model::getActiveValidators()
傳回適用於目前 $scenario 的驗證器。
public yii\validators\Validator[] getActiveValidators ( $attribute = null ) | ||
$attribute | string|null |
應回傳其適用驗證器的屬性名稱。如果為 null,將回傳模型中所有屬性的驗證器。 |
return | yii\validators\Validator[] |
適用於目前 $scenario 的驗證器。 |
---|
public function getActiveValidators($attribute = null)
{
$activeAttributes = $this->activeAttributes();
if ($attribute !== null && !in_array($attribute, $activeAttributes, true)) {
return [];
}
$scenario = $this->getScenario();
$validators = [];
foreach ($this->getValidators() as $validator) {
if ($attribute === null) {
$validatorAttributes = $validator->getValidationAttributes($activeAttributes);
$attributeValid = !empty($validatorAttributes);
} else {
$attributeValid = in_array($attribute, $validator->getValidationAttributes($attribute), true);
}
if ($attributeValid && $validator->isActive($scenario)) {
$validators[] = $validator;
}
}
return $validators;
}
public string getAttributeHint ( $attribute ) | ||
$attribute | 字串 |
屬性名稱 |
return | 字串 |
屬性提示 |
---|
public function getAttributeHint($attribute)
{
$hints = $this->attributeHints();
return isset($hints[$attribute]) ? $hints[$attribute] : '';
}
public string getAttributeLabel ( $attribute ) | ||
$attribute | 字串 |
屬性名稱 |
return | 字串 |
屬性標籤 |
---|
public function getAttributeLabel($attribute)
{
$labels = $this->attributeLabels();
return isset($labels[$attribute]) ? $labels[$attribute] : $this->generateAttributeLabel($attribute);
}
定義於: yii\base\Model::getAttributes()
傳回屬性值。
public array getAttributes ( $names = null, $except = [] ) | ||
$names | array|null |
需要回傳其值的屬性列表。預設為 null,表示將回傳 attributes() 中列出的所有屬性。如果它是陣列,則只會回傳陣列中的屬性。 |
$except | 陣列 |
不應回傳其值的屬性列表。 |
return | 陣列 |
屬性值 (名稱 => 值)。 |
---|
public function getAttributes($names = null, $except = [])
{
$values = [];
if ($names === null) {
$names = $this->attributes();
}
foreach ($names as $name) {
$values[$name] = $this->$name;
}
foreach ($except as $name) {
unset($values[$name]);
}
return $values;
}
定義於: yii\base\Component::getBehavior()
傳回具名的行為物件。
public yii\base\Behavior|null getBehavior ( $name ) | ||
$name | 字串 |
行為名稱 |
return | yii\base\Behavior|null |
行為物件,如果行為不存在,則為 null |
---|
public function getBehavior($name)
{
$this->ensureBehaviors();
return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
}
定義於: yii\base\Component::getBehaviors()
傳回附加到此元件的所有行為。
public yii\base\Behavior[] getBehaviors ( ) | ||
return | yii\base\Behavior[] |
附加到此組件的行為列表 |
---|
public function getBehaviors()
{
$this->ensureBehaviors();
return $this->_behaviors;
}
public array getErrorSummary ( $showAllErrors ) | ||
$showAllErrors | boolean |
布林值,如果設定為 true,將顯示每個屬性的每個錯誤訊息,否則只會顯示每個屬性的第一個錯誤訊息。 |
return | 陣列 |
所有屬性的錯誤,以一維陣列形式呈現。如果沒有錯誤,則回傳空陣列。 |
---|
public function getErrorSummary($showAllErrors)
{
$lines = [];
$errors = $showAllErrors ? $this->getErrors() : $this->getFirstErrors();
foreach ($errors as $es) {
$lines = array_merge($lines, (array)$es);
}
return $lines;
}
public array getErrors ( $attribute = null ) | ||
$attribute | string|null |
屬性名稱。使用 null 檢索所有屬性的錯誤。 |
return | 陣列 |
所有屬性或指定屬性的錯誤。如果沒有錯誤,則回傳空陣列。請參閱 getErrors() 以取得詳細描述。請注意,當回傳所有屬性的錯誤時,結果是二維陣列,如下所示
|
---|
public function getErrors($attribute = null)
{
if ($attribute === null) {
return $this->_errors === null ? [] : $this->_errors;
}
return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : [];
}
public string|null getFirstError ( $attribute ) | ||
$attribute | 字串 |
屬性名稱。 |
return | string|null |
錯誤訊息。如果沒有錯誤,則回傳 Null。 |
---|
public function getFirstError($attribute)
{
return isset($this->_errors[$attribute]) ? reset($this->_errors[$attribute]) : null;
}
public array getFirstErrors ( ) | ||
return | 陣列 |
第一個錯誤。陣列的鍵名是屬性名稱,陣列的值是相應的錯誤訊息。如果沒有錯誤,將返回一個空陣列。 |
---|
public function getFirstErrors()
{
if (empty($this->_errors)) {
return [];
}
$errors = [];
foreach ($this->_errors as $name => $es) {
if (!empty($es)) {
$errors[$name] = reset($es);
}
}
return $errors;
}
public ArrayIterator getIterator ( ) | ||
return | ArrayIterator |
用於遍歷列表中項目的迭代器。 |
---|
#[\ReturnTypeWillChange]
public function getIterator()
{
$attributes = $this->getAttributes();
return new ArrayIterator($attributes);
}
public string getScenario ( ) | ||
return | 字串 |
此模型所處的情境。預設為 SCENARIO_DEFAULT。 |
---|
public function getScenario()
{
return $this->_scenario;
}
定義於: yii\base\Model::getValidators()
傳回 rules() 中宣告的所有驗證器。
此方法與 getActiveValidators() 的不同之處在於,後者僅返回適用於當前 $scenario 的驗證器。
由於此方法返回 ArrayObject 物件,您可以透過插入或移除驗證器來操作它(在模型行為中很有用)。例如:
$model->validators[] = $newValidator;
public ArrayObject|yii\validators\Validator[] getValidators ( ) | ||
return | ArrayObject|yii\validators\Validator[] |
模型中宣告的所有驗證器。 |
---|
public function getValidators()
{
if ($this->_validators === null) {
$this->_validators = $this->createValidators();
}
return $this->_validators;
}
傳回值,指出模型是否具有指定名稱的屬性。
public boolean hasAttribute ( $name ) | ||
$name | 字串 |
屬性的名稱。 |
return | boolean |
模型是否具有指定名稱的屬性。 |
---|
public function hasAttribute($name)
{
return array_key_exists($name, $this->_attributes);
}
定義於: yii\base\Model::hasErrors()
傳回值,指出是否有任何驗證錯誤。
public boolean hasErrors ( $attribute = null ) | ||
$attribute | string|null |
屬性名稱。使用 null 以檢查所有屬性。 |
return | boolean |
是否存在任何錯誤。 |
---|
public function hasErrors($attribute = null)
{
return $attribute === null ? !empty($this->_errors) : isset($this->_errors[$attribute]);
}
定義於: yii\base\Component::hasEventHandlers()
傳回值,指出是否有名稱事件附加任何處理常式。
public boolean hasEventHandlers ( $name ) | ||
$name | 字串 |
事件名稱 |
return | 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);
}
定義於: yii\base\Component::hasMethod()
傳回值,指出是否已定義方法。
方法被定義如果:
- 類別具有指定名稱的方法
- 附加的行為具有給定名稱的方法(當
$checkBehaviors
為 true 時)。
public boolean hasMethod ( $name, $checkBehaviors = true ) | ||
$name | 字串 |
屬性名稱 |
$checkBehaviors | boolean |
是否將行為的方法視為此組件的方法 |
return | 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;
}
定義於: yii\base\Component::hasProperty()
傳回值,指出是否為此元件定義屬性。
屬性被定義如果:
- 類別具有與指定名稱相關聯的 getter 或 setter 方法(在這種情況下,屬性名稱不區分大小寫);
- 類別具有具有指定名稱的成員變數 (當
$checkVars
為 true 時); - 附加的行為具有給定名稱的屬性(當
$checkBehaviors
為 true 時)。
另請參閱
public boolean hasProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | 字串 |
屬性名稱 |
$checkVars | boolean |
是否將成員變數視為屬性 |
$checkBehaviors | boolean |
是否將行為的屬性視為此組件的屬性 |
return | boolean |
屬性是否被定義 |
---|
public function hasProperty($name, $checkVars = true, $checkBehaviors = true)
{
return $this->canGetProperty($name, $checkVars, $checkBehaviors) || $this->canSetProperty($name, false, $checkBehaviors);
}
public void init ( ) |
public function init()
{
}
定義於: yii\base\StaticInstanceTrait::instance()
傳回靜態類別實例,可用於取得 meta 資訊。
public static static instance ( $refresh = false ) | ||
$refresh | boolean |
即使靜態實例已經被緩存,是否重新建立它。 |
return | yii\base\DynamicModel |
類別實例。 |
---|
public static function instance($refresh = false)
{
$className = get_called_class();
if ($refresh || !isset(self::$_instances[$className])) {
self::$_instances[$className] = Yii::createObject($className);
}
return self::$_instances[$className];
}
public boolean isAttributeActive ( $attribute ) | ||
$attribute | 字串 |
屬性名稱 |
return | boolean |
屬性在目前情境中是否為啟用狀態 |
---|
public function isAttributeActive($attribute)
{
return in_array($attribute, $this->activeAttributes(), true);
}
定義於: yii\base\Model::isAttributeRequired()
傳回值,指出屬性是否為必要。
這取決於檢查屬性是否與目前 $scenario 中的 required 驗證規則相關聯。
請注意,當驗證器使用 $when 應用條件驗證時,此方法將返回 false
,無論 when
條件如何,因為它可能在模型載入資料之前被調用。
public boolean isAttributeRequired ( $attribute ) | ||
$attribute | 字串 |
屬性名稱 |
return | boolean |
屬性是否為必要項 |
---|
public function isAttributeRequired($attribute)
{
foreach ($this->getActiveValidators($attribute) as $validator) {
if ($validator instanceof RequiredValidator && $validator->when === null) {
return true;
}
}
return false;
}
public boolean isAttributeSafe ( $attribute ) | ||
$attribute | 字串 |
屬性名稱 |
return | boolean |
屬性是否對於大量賦值是安全的 |
---|
public function isAttributeSafe($attribute)
{
return in_array($attribute, $this->safeAttributes(), true);
}
使用輸入資料填入模型。
此方法為以下操作提供了一個方便的捷徑:
if (isset($_POST['FormName'])) {
$model->attributes = $_POST['FormName'];
if ($model->save()) {
// handle success
}
}
使用 load()
可以寫成:
if ($model->load($_POST) && $model->save()) {
// handle success
}
load()
從模型的 formName() 方法取得 'FormName'
(您可以覆寫此方法),除非給定了 $formName
參數。如果表單名稱為空,load()
將使用整個 $data
填充模型,而不是 $data['FormName']
。
請注意,要填充的資料會受到 setAttributes() 的安全檢查。
public boolean load ( $data, $formName = null ) | ||
$data | 陣列 |
要載入的資料陣列,通常為 |
$formName | string|null |
用於將資料載入模型的表單名稱,不使用表單時為空字串。如果未設定,則使用 formName()。 |
return | boolean |
|
---|
public function load($data, $formName = null)
{
$scope = $formName === null ? $this->formName() : $formName;
if ($scope === '' && !empty($data)) {
$this->setAttributes($data);
return true;
} elseif (isset($data[$scope])) {
$this->setAttributes($data[$scope]);
return true;
}
return false;
}
定義於: yii\base\Model::loadMultiple()
使用來自終端使用者的資料填入一組模型。
此方法主要用於收集表格資料輸入。每個模型要載入的資料是 $data[formName][index]
,其中 formName
指的是 formName() 的值,而 index
是模型在 $models
陣列中的索引。如果 formName() 為空,則將使用 $data[index]
來填充每個模型。填充到每個模型的資料會受到 setAttributes() 的安全檢查。
public static boolean loadMultiple ( $models, $data, $formName = null ) | ||
$models | 陣列 |
要填充的模型。請注意,所有模型應具有相同的類別。 |
$data | 陣列 |
資料陣列。這通常是 |
$formName | string|null |
用於將資料載入模型的表單名稱。如果未設定,它將使用 |
return | boolean |
是否至少有一個模型成功填充。 |
---|
public static function loadMultiple($models, $data, $formName = null)
{
if ($formName === null) {
/* @var $first Model|false */
$first = reset($models);
if ($first === false) {
return false;
}
$formName = $first->formName();
}
$success = false;
foreach ($models as $i => $model) {
/* @var $model Model */
if ($formName == '') {
if (!empty($data[$i]) && $model->load($data[$i], '')) {
$success = true;
}
} elseif (!empty($data[$formName][$i]) && $model->load($data[$formName][$i], '')) {
$success = true;
}
}
return $success;
}
定義於: yii\base\Component::off()
從此元件分離現有的事件處理常式。
此方法與 on() 相反。
注意:如果為事件名稱傳遞了萬用字元模式,則只會移除使用此萬用字元註冊的處理器,而使用符合此萬用字元的純名稱註冊的處理器將保留。
另請參閱 on()。
public boolean off ( $name, $handler = null ) | ||
$name | 字串 |
事件名稱 |
$handler | callable|null |
要移除的事件處理器。如果為 null,將移除附加到指定名稱事件的所有處理器。 |
return | 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;
}
定義於: yii\base\Model::offsetExists()
傳回在指定偏移量處是否有元素。
此方法為 SPL 介面 ArrayAccess 所要求。當您使用類似 isset($model[$offset])
的語法時,它會被隱式調用。
public boolean offsetExists ( $offset ) | ||
$offset | 字串 |
要檢查的偏移量。 |
return | boolean |
偏移量是否存在。 |
---|
#[\ReturnTypeWillChange]
public function offsetExists($offset)
{
return isset($this->$offset);
}
定義於: yii\base\Model::offsetGet()
傳回指定偏移量處的元素。
此方法為 SPL 介面 ArrayAccess 所要求。當您使用類似 $value = $model[$offset];
的語法時,它會被隱式調用。
public mixed offsetGet ( $offset ) | ||
$offset | 字串 |
要檢索元素的偏移量。 |
return | mixed |
偏移量處的元素,如果在偏移量處未找到元素則為 null |
---|
#[\ReturnTypeWillChange]
public function offsetGet($offset)
{
return $this->$offset;
}
定義於: yii\base\Model::offsetSet()
設定指定偏移量處的元素。
此方法為 SPL 介面 ArrayAccess 所要求。當您使用類似 $model[$offset] = $value;
的語法時,它會被隱式調用。
public void offsetSet ( $offset, $value ) | ||
$offset | 字串 |
要設定元素的偏移量 |
$value | mixed |
元素值 |
#[\ReturnTypeWillChange]
public function offsetSet($offset, $value)
{
$this->$offset = $value;
}
定義於: yii\base\Model::offsetUnset()
將指定偏移量處的元素值設定為 null。
此方法為 SPL 介面 ArrayAccess 所要求。當您使用類似 unset($model[$offset])
的語法時,它會被隱式調用。
public void offsetUnset ( $offset ) | ||
$offset | 字串 |
要取消設定元素的偏移量 |
#[\ReturnTypeWillChange]
public function offsetUnset($offset)
{
$this->$offset = null;
}
將事件處理常式附加到事件。
事件處理器必須是有效的 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 | 字串 |
事件名稱 |
$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]);
}
}
定義於: yii\base\Model::onUnsafeAttribute()
當大量指派不安全的屬性時,會調用此方法。
預設實作將在 YII_DEBUG 開啟時記錄警告訊息。否則它不執行任何操作。
public void onUnsafeAttribute ( $name, $value ) | ||
$name | 字串 |
不安全屬性的名稱 |
$value | mixed |
屬性值 |
public function onUnsafeAttribute($name, $value)
{
if (YII_DEBUG) {
Yii::debug("Failed to set unsafe attribute '$name' in '" . get_class($this) . "'.", __METHOD__);
}
}
定義於: yii\base\ArrayableTrait::resolveFields()
判斷哪些欄位可由 toArray() 傳回。
此方法將首先從給定的欄位中提取根欄位。然後,它將針對在 fields() 和 extraFields() 中宣告的根欄位檢查請求的根欄位,以確定可以返回哪些欄位。
protected array resolveFields ( array $fields, array $expand ) | ||
$fields | 陣列 |
請求導出的欄位 |
$expand | 陣列 |
請求導出的額外欄位 |
return | 陣列 |
要導出的欄位列表。陣列的鍵名是欄位名稱,陣列的值是相應的物件屬性名稱或返回欄位值的 PHP 可調用物件。 |
---|
protected function resolveFields(array $fields, array $expand)
{
$fields = $this->extractRootFields($fields);
$expand = $this->extractRootFields($expand);
$result = [];
foreach ($this->fields() as $field => $definition) {
if (is_int($field)) {
$field = $definition;
}
if (empty($fields) || in_array($field, $fields, true)) {
$result[$field] = $definition;
}
}
if (empty($expand)) {
return $result;
}
foreach ($this->extraFields() as $field => $definition) {
if (is_int($field)) {
$field = $definition;
}
if (in_array($field, $expand, true)) {
$result[$field] = $definition;
}
}
return $result;
}
傳回屬性的驗證規則。
驗證規則由 validate() 使用,以檢查屬性值是否有效。子類別可以覆寫此方法以宣告不同的驗證規則。
每個規則都是一個具有以下結構的陣列:
[
['attribute1', 'attribute2'],
'validator type',
'on' => ['scenario1', 'scenario2'],
//...other parameters...
]
其中:
- 屬性列表:必要,指定要驗證的屬性陣列,對於單個屬性,您可以傳遞字串;
- 驗證器類型:必要,指定要使用的驗證器。它可以是內建的驗證器名稱、模型類別的方法名稱、匿名函數或驗證器類別名稱。
- on:可選,指定可以應用驗證規則的 情境 陣列。如果未設定此選項,則規則將應用於所有情境。
- 可以指定其他名稱-值對來初始化相應的驗證器屬性。有關可能的屬性,請參閱個別驗證器類別 API。
驗證器可以是擴展 yii\validators\Validator 的類別的物件,或模型類別方法(稱為內聯驗證器),它具有以下簽名:
// $params refers to validation parameters given in the rule
function validatorName($attribute, $params)
在上面的程式碼中,$attribute
指的是當前正在驗證的屬性,而 $params
包含驗證器配置選項的陣列,例如 string
驗證器的 max
。目前正在驗證的屬性的值可以作為 $this->$attribute
存取。請注意 attribute
之前的 $
;這是取得變數 $attribute
的值,並將其用作要存取的屬性的名稱。
Yii 也提供了一組 內建驗證器。每個驗證器都有一個別名,可以在指定驗證規則時使用。
以下是一些範例:
[
// built-in "required" validator
[['username', 'password'], 'required'],
// built-in "string" validator customized with "min" and "max" properties
['username', 'string', 'min' => 3, 'max' => 12],
// built-in "compare" validator that is used in "register" scenario only
['password', 'compare', 'compareAttribute' => 'password2', 'on' => 'register'],
// an inline validator defined via the "authenticate()" method in the model class
['password', 'authenticate', 'on' => 'login'],
// a validator of class "DateRangeValidator"
['dateRange', 'DateRangeValidator'],
];
請注意,為了繼承父類別中定義的規則,子類別需要使用 array_merge()
等函數將父規則與子規則合併。
另請參閱 scenarios()。
public array rules ( ) | ||
return | 陣列 |
驗證規則 |
---|
public function rules()
{
return [];
}
定義於: yii\base\Model::safeAttributes()
傳回在目前情境中大量指派為安全的屬性名稱。
public string[] safeAttributes ( ) | ||
return | 字串[] |
安全屬性名稱 |
---|
public function safeAttributes()
{
$scenario = $this->getScenario();
$scenarios = $this->scenarios();
if (!isset($scenarios[$scenario])) {
return [];
}
$attributes = [];
foreach ($scenarios[$scenario] as $attribute) {
if (
$attribute !== ''
&& strncmp($attribute, '!', 1) !== 0
&& !in_array('!' . $attribute, $scenarios[$scenario])
) {
$attributes[] = $attribute;
}
}
return $attributes;
}
定義於: yii\base\Model::scenarios()
傳回情境列表和對應的作用中屬性。
活動屬性是在目前情境中需要驗證的屬性。返回的陣列應採用以下格式:
[
'scenario1' => ['attribute11', 'attribute12', ...],
'scenario2' => ['attribute21', 'attribute22', ...],
...
]
預設情況下,活動屬性被認為是安全的,並且可以大量賦值。如果屬性不應大量賦值(因此被認為是不安全的),請在屬性前加上驚嘆號字元(例如 '!rank'
)。
此方法的預設實作將返回在 rules() 宣告中找到的所有情境。名為 SCENARIO_DEFAULT 的特殊情境將包含在 rules() 中找到的所有屬性。每個情境都將與適用於該情境的驗證規則正在驗證的屬性相關聯。
public array scenarios ( ) | ||
return | 陣列 |
情境列表和相應的活動屬性。 |
---|
public function scenarios()
{
$scenarios = [self::SCENARIO_DEFAULT => []];
foreach ($this->getValidators() as $validator) {
foreach ($validator->on as $scenario) {
$scenarios[$scenario] = [];
}
foreach ($validator->except as $scenario) {
$scenarios[$scenario] = [];
}
}
$names = array_keys($scenarios);
foreach ($this->getValidators() as $validator) {
if (empty($validator->on) && empty($validator->except)) {
foreach ($names as $name) {
foreach ($validator->attributes as $attribute) {
$scenarios[$name][$attribute] = true;
}
}
} elseif (empty($validator->on)) {
foreach ($names as $name) {
if (!in_array($name, $validator->except, true)) {
foreach ($validator->attributes as $attribute) {
$scenarios[$name][$attribute] = true;
}
}
}
} else {
foreach ($validator->on as $name) {
foreach ($validator->attributes as $attribute) {
$scenarios[$name][$attribute] = true;
}
}
}
}
foreach ($scenarios as $scenario => $attributes) {
if (!empty($attributes)) {
$scenarios[$scenario] = array_keys($attributes);
}
}
return $scenarios;
}
設定單一屬性的標籤。
public $this setAttributeLabel ( $attribute, $label ) | ||
$attribute | 字串 |
屬性名稱。 |
$label | 字串 |
屬性標籤值。 |
public function setAttributeLabel($attribute, $label)
{
$this->_attributeLabels[$attribute] = $label;
return $this;
}
設定所有屬性的標籤。
public $this setAttributeLabels ( array $labels = [] ) | ||
$labels | 字串[] |
屬性標籤。 |
public function setAttributeLabels(array $labels = [])
{
$this->_attributeLabels = $labels;
return $this;
}
public void setAttributes ( $values, $safeOnly = true ) | ||
$values | 陣列 |
要指派給模型的屬性值 (名稱 => 值)。 |
$safeOnly | boolean |
是否僅應對安全屬性進行指派。安全屬性是指與目前 $scenario 中的驗證規則相關聯的屬性。 |
public function setAttributes($values, $safeOnly = true)
{
if (is_array($values)) {
$attributes = array_flip($safeOnly ? $this->safeAttributes() : $this->attributes());
foreach ($values as $name => $value) {
if (isset($attributes[$name])) {
$this->$name = $value;
} elseif ($safeOnly) {
$this->onUnsafeAttribute($name, $value);
}
}
}
}
public void setScenario ( $value ) | ||
$value | 字串 |
此模型所處的情境。 |
public function setScenario($value)
{
$this->_scenario = $value;
}
Defined in: yii\base\ArrayableTrait::toArray()
將模型轉換為陣列。
此方法將首先呼叫 resolveFields(),以識別要包含在結果陣列中的欄位。然後,它會將模型轉換為包含這些欄位的陣列。如果 $recursive
為 true,則任何嵌入式物件也將轉換為陣列。當嵌入式物件為 yii\base\Arrayable 時,它們各自的巢狀欄位將被提取並傳遞給 toArray()。
如果模型實作了 yii\web\Linkable 介面,則結果陣列也將具有一個 _link
元素,該元素引用介面指定的連結清單。
public array toArray ( array $fields = [], array $expand = [], $recursive = true ) | ||
$fields | 陣列 |
正在請求的欄位。如果為空或包含 '*',則將傳回 fields() 指定的所有欄位。欄位可以是巢狀的,並以點 (.) 分隔。例如:item.field.sub-field |
$expand | 陣列 |
正在請求用於匯出的其他欄位。僅考慮在 extraFields() 中宣告的欄位。Expand 也可以是巢狀的,並以點 (.) 分隔。例如:item.expand1.expand2 |
$recursive | boolean |
是否遞迴傳回嵌入式物件的陣列表示形式。 |
return | 陣列 |
物件的陣列表示形式 |
---|
public function toArray(array $fields = [], array $expand = [], $recursive = true)
{
$data = [];
foreach ($this->resolveFields($fields, $expand) as $field => $definition) {
$attribute = is_string($definition) ? $this->$definition : $definition($this, $field);
if ($recursive) {
$nestedFields = $this->extractFieldsFor($fields, $field);
$nestedExpand = $this->extractFieldsFor($expand, $field);
if ($attribute instanceof Arrayable) {
$attribute = $attribute->toArray($nestedFields, $nestedExpand);
} elseif ($attribute instanceof \JsonSerializable) {
$attribute = $attribute->jsonSerialize();
} elseif (is_array($attribute)) {
$attribute = array_map(
function ($item) use ($nestedFields, $nestedExpand) {
if ($item instanceof Arrayable) {
return $item->toArray($nestedFields, $nestedExpand);
} elseif ($item instanceof \JsonSerializable) {
return $item->jsonSerialize();
}
return $item;
},
$attribute
);
}
}
$data[$field] = $attribute;
}
if ($this instanceof Linkable) {
$data['_links'] = Link::serialize($this->getLinks());
}
return $recursive ? ArrayHelper::toArray($data) : $data;
}
public void trigger ( $name, yii\base\Event $event = null ) | ||
$name | 字串 |
事件名稱 |
$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);
}
取消定義屬性。
public void undefineAttribute ( $name ) | ||
$name | 字串 |
屬性名稱。 |
public function undefineAttribute($name)
{
unset($this->_attributes[$name]);
}
Defined in: yii\base\Model::validate()
執行資料驗證。
此方法執行適用於目前 $scenario 的驗證規則。以下準則用於判斷規則目前是否適用
- 規則必須與目前情境相關的屬性相關聯;
- 規則對於目前情境必須有效。
此方法將分別在實際驗證之前和之後呼叫 beforeValidate() 和 afterValidate()。如果 beforeValidate() 傳回 false,則驗證將被取消,並且不會呼叫 afterValidate()。
在驗證期間發現的錯誤可以通過 getErrors()、 getFirstErrors() 和 getFirstError() 檢索。
public boolean validate ( $attributeNames = null, $clearErrors = true ) | ||
$attributeNames | string[]|string|null |
應驗證的屬性名稱或屬性名稱清單。如果此參數為空,則表示應驗證適用驗證規則中列出的任何屬性。 |
$clearErrors | boolean |
是否在執行驗證之前呼叫 clearErrors() |
return | boolean |
驗證是否成功且沒有任何錯誤。 |
---|---|---|
throws | yii\base\InvalidArgumentException |
如果目前情境未知。 |
public function validate($attributeNames = null, $clearErrors = true)
{
if ($clearErrors) {
$this->clearErrors();
}
if (!$this->beforeValidate()) {
return false;
}
$scenarios = $this->scenarios();
$scenario = $this->getScenario();
if (!isset($scenarios[$scenario])) {
throw new InvalidArgumentException("Unknown scenario: $scenario");
}
if ($attributeNames === null) {
$attributeNames = $this->activeAttributes();
}
$attributeNames = (array)$attributeNames;
foreach ($this->getActiveValidators() as $validator) {
$validator->validateAttributes($this, $attributeNames);
}
$this->afterValidate();
return !$this->hasErrors();
}
使用指定的驗證規則驗證給定的資料。
此方法將建立 DynamicModel 實例,使用要驗證的資料填充它,建立指定的驗證規則,然後使用這些規則驗證資料。
public static static validateData ( array $data, $rules = [] ) | ||
$data | 陣列 |
要驗證的資料(名稱-值 組)。 |
$rules | 陣列 |
驗證規則。關於此參數的格式,請參閱 yii\base\Model::rules()。 |
return | yii\base\DynamicModel |
包含要驗證資料的模型實例。 |
---|---|---|
throws | yii\base\InvalidConfigException |
如果驗證規則未正確指定。 |
public static function validateData(array $data, $rules = [])
{
/* @var $model DynamicModel */
$model = new static($data);
if (!empty($rules)) {
$validators = $model->getValidators();
foreach ($rules as $rule) {
if ($rule instanceof Validator) {
$validators->append($rule);
$model->defineAttributesByValidator($rule);
} elseif (is_array($rule) && isset($rule[0], $rule[1])) { // attributes, validator type
$validator = Validator::createValidator($rule[1], $model, (array)$rule[0], array_slice($rule, 2));
$validators->append($validator);
$model->defineAttributesByValidator($validator);
} else {
throw new InvalidConfigException('Invalid validation rule: a rule must specify both attribute names and validator type.');
}
}
}
$model->validate();
return $model;
}
public static boolean validateMultiple ( $models, $attributeNames = null ) | ||
$models | 陣列 |
要驗證的模型 |
$attributeNames | array|null |
應驗證的屬性名稱清單。如果此參數為空,則表示應驗證適用驗證規則中列出的任何屬性。 |
return | boolean |
是否所有模型都有效。如果一個或多個模型具有驗證錯誤,將傳回 False。 |
---|
public static function validateMultiple($models, $attributeNames = null)
{
$valid = true;
/* @var $model Model */
foreach ($models as $model) {
$valid = $model->validate($attributeNames) && $valid;
}
return $valid;
}
註冊 或 登入 以發表評論。