類別 yii\data\DataFilter
DataFilter 是一個特殊的 yii\base\Model,用於處理查詢過濾條件。
它允許驗證和建立透過請求傳遞的過濾條件。
過濾器範例
{
"or": [
{
"and": [
{
"name": "some name",
},
{
"price": "25",
}
]
},
{
"id": {"in": [2, 5, 9]},
"price": {
"gt": 10,
"lt": 50
}
}
]
}
在請求中,過濾器應使用與 $filterAttributeName 相等的鍵名來指定。因此,實際的 HTTP 請求主體將如下所示:
{
"filter": {"or": {...}},
"page": 2,
...
}
原始過濾器值應指派給模型的 $filter 屬性。您可以透過 load() 方法從請求資料中填充它
use yii\data\DataFilter;
$dataFilter = new DataFilter();
$dataFilter->load(Yii::$app->request->getBodyParams());
為了使此類別運作,它需要透過 $searchModel 指定的搜尋模型。此搜尋模型應宣告所有可用的搜尋屬性及其驗證規則。例如
class SearchModel extends \yii\base\Model
{
public $id;
public $name;
public function rules()
{
return [
[['id', 'name'], 'trim'],
['id', 'integer'],
['name', 'string'],
];
}
}
為了減少類別數量,您可以將 yii\base\DynamicModel 實例用作 $searchModel。在這種情況下,您應該使用 PHP callable 指定 $searchModel
function () {
return (new \yii\base\DynamicModel(['id' => null, 'name' => null]))
->addRule(['id', 'name'], 'trim')
->addRule('id', 'integer')
->addRule('name', 'string');
}
您可以使用 validate() 方法來檢查過濾器值是否有效。如果驗證失敗,您可以使用 getErrors() 來取得實際的錯誤訊息。
為了取得適用於提取資料的過濾條件,請使用 build() 方法。
注意:這是一個基礎類別。它對 build() 的實作僅返回標準化的 $filter 值。為了將過濾器轉換為特定格式,您應使用此類別的後代類別,該類別相應地實作 buildInternal() 方法。
公開屬性
公開方法
保護方法
事件
事件 | 類型 | 描述 | 定義於 |
---|---|---|---|
EVENT_AFTER_VALIDATE | yii\base\Event | 在 validate() 結束時引發的事件 | yii\base\Model |
EVENT_BEFORE_VALIDATE | yii\base\ModelEvent | 在 validate() 開始時引發的事件。 | yii\base\Model |
常數
常數 | 值 | 描述 | 定義於 |
---|---|---|---|
SCENARIO_DEFAULT | 'default' | 預設場景的名稱。 | yii\base\Model |
TYPE_ARRAY | 'array' | yii\data\DataFilter | |
TYPE_BOOLEAN | 'boolean' | yii\data\DataFilter | |
TYPE_DATE | 'date' | yii\data\DataFilter | |
TYPE_DATETIME | 'datetime' | yii\data\DataFilter | |
TYPE_FLOAT | 'float' | yii\data\DataFilter | |
TYPE_INTEGER | 'integer' | yii\data\DataFilter | |
TYPE_STRING | 'string' | yii\data\DataFilter | |
TYPE_TIME | 'time' | yii\data\DataFilter |
屬性詳情
要在搜尋條件中使用的實際屬性名稱,格式為:[filterAttribute => actualAttribute]。例如,在使用表格聯接進行搜尋查詢的情況下,屬性映射可能如下所示
[
'authorName' => '{{author}}.[[name]]'
]
屬性映射將在 normalize() 方法中應用於過濾條件。
將過濾條件關鍵字映射到驗證方法。這些方法由 validateCondition() 使用,以驗證原始過濾條件。
'AND' => 'validateConjunctionCondition',
'OR' => 'validateConjunctionCondition',
'NOT' => 'validateBlockCondition',
'<' => 'validateOperatorCondition',
'>' => 'validateOperatorCondition',
'<=' => 'validateOperatorCondition',
'>=' => 'validateOperatorCondition',
'=' => 'validateOperatorCondition',
'!=' => 'validateOperatorCondition',
'IN' => 'validateOperatorCondition',
'NOT IN' => 'validateOperatorCondition',
'LIKE' => 'validateOperatorCondition',
]
格式為 [errorKey => message]
的錯誤訊息。請注意,此屬性的類型在 getter 和 setter 中有所不同。有關詳細資訊,請參閱 getErrorMessages() 和 setErrorMessages()。
透過 $filterAttributeName 指定的過濾器屬性的標籤。它將在錯誤訊息組成期間使用。
處理過濾器值的屬性名稱。該名稱用於透過 load() 方法載入資料。
可能在過濾器中使用的關鍵字或表達式。陣列鍵是從使用者請求取得的原始過濾器值中使用的表達式。陣列值是此類別方法中使用的內部建立鍵。
任何未指定的關鍵字將不會被識別為過濾器控制,並且將被視為屬性名稱。因此,您應避免控制關鍵字和屬性名稱之間發生衝突。例如:如果您有控制關鍵字 'like' 和一個名為 'like' 的屬性,則指定此類屬性的條件將是不可能的。
您可以為同一個過濾器建立鍵指定多個關鍵字,從而建立多個別名。例如
[
'eq' => '=',
'=' => '=',
'==' => '=',
'===' => '=',
// ...
]
注意:在指定過濾器控制時,請考慮您的 API 使用的實際資料交換格式。確保每個指定的控制關鍵字對於該格式都有效。例如,在 XML 中,標籤名稱只能以字母字元開頭,因此像
>
、'=' 或$gt
這樣的控制項將會破壞 XML 結構描述。
'and' => 'AND',
'or' => 'OR',
'not' => 'NOT',
'lt' => '<',
'gt' => '>',
'lte' => '<=',
'gte' => '>=',
'eq' => '=',
'neq' => '!=',
'in' => 'IN',
'nin' => 'NOT IN',
'like' => 'LIKE',
]
null
的表示形式,以代替無法使用 literal null
的情況。
指定每個運算符支援的搜尋屬性類型列表。此欄位應採用以下格式:'operatorKeyword' => ['type1', 'type2' ...]。支援的類型列表可以指定為 *
,表示運算符支援所有可用類型。任何未指定的關鍵字將不被視為有效的運算符。
'<' => [
self::TYPE_INTEGER,
self::TYPE_FLOAT,
self::TYPE_DATETIME,
self::TYPE_DATE,
self::TYPE_TIME,
],
'>' => [
self::TYPE_INTEGER,
self::TYPE_FLOAT,
self::TYPE_DATETIME,
self::TYPE_DATE,
self::TYPE_TIME,
],
'<=' => [
self::TYPE_INTEGER,
self::TYPE_FLOAT,
self::TYPE_DATETIME,
self::TYPE_DATE,
self::TYPE_TIME,
],
'>=' => [
self::TYPE_INTEGER,
self::TYPE_FLOAT,
self::TYPE_DATETIME,
self::TYPE_DATE,
self::TYPE_TIME,
],
'=' => '*',
'!=' => '*',
'IN' => '*',
'NOT IN' => '*',
'LIKE' => [
self::TYPE_STRING,
],
]
搜尋屬性類型映射。請注意,此屬性的類型在 getter 和 setter 中有所不同。有關詳細資訊,請參閱 getSearchAttributeTypes() 和 setSearchAttributeTypes()。
模型實例。 請注意,此屬性的類型在 getter 和 setter 中有所不同。 詳情請參閱 getSearchModel() 和 setSearchModel()。
方法詳情
定義於: yii\base\Component::__call()
調用指定的非類別方法。
此方法將檢查是否有任何附加的行為具有指定名稱的方法,如果有的話將會執行它。
請勿直接呼叫此方法,因為它是一個 PHP 魔術方法,當未知的的方法被調用時,它會被隱式地呼叫。
public mixed __call ( $name, $params ) | ||
$name | string |
方法名稱 |
$params | array |
方法參數 |
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;
}
定義於: yii\base\BaseObject::__construct()
建構子。
預設實作會做兩件事
- 使用給定的組態
$config
初始化物件。 - 呼叫 init()。
如果子類別覆寫了這個方法,建議
- 建構子的最後一個參數是一個組態陣列,就像此處的
$config
一樣。 - 在建構子的結尾呼叫父類別的實作。
public void __construct ( $config = [] ) | ||
$config | array |
將用於初始化物件屬性的 名稱-值 配對 |
public function __construct($config = [])
{
if (!empty($config)) {
Yii::configure($this, $config);
}
$this->init();
}
返回組件屬性的值。
此方法將依以下順序檢查並採取相應的動作
- getter 定義的屬性:回傳 getter 結果
- 行為的屬性:回傳行為屬性值
請勿直接呼叫此方法,因為它是一個 PHP 魔術方法,當執行 $value = $component->property;
時,它會被隱式地呼叫。
public mixed __get ( $name ) | ||
$name | string |
屬性名稱 |
return | mixed |
屬性值或行為的屬性值 |
---|---|---|
throws | yii\base\UnknownPropertyException |
如果屬性未定義 |
throws | yii\base\InvalidCallException |
如果屬性是唯寫的。 |
public function __get($name)
{
if ($name === $this->filterAttributeName) {
return $this->getFilter();
}
return parent::__get($name);
}
檢查屬性是否已設定,即已定義且不為 null。
此方法將依以下順序檢查並採取相應的動作
- setter 定義的屬性:回傳屬性是否已設定
- 行為的屬性:回傳屬性是否已設定
- 對於不存在的屬性回傳
false
請勿直接呼叫此方法,因為它是一個 PHP 魔術方法,當執行 isset($component->property)
時,它會被隱式地呼叫。
public boolean __isset ( $name ) | ||
$name | string |
屬性名稱或事件名稱 |
return | boolean |
具名的屬性是否已設定 |
---|
public function __isset($name)
{
if ($name === $this->filterAttributeName) {
return $this->getFilter() !== null;
}
return parent::__isset($name);
}
設定組件屬性的值。
此方法將依以下順序檢查並採取相應的動作
- setter 定義的屬性:設定屬性值
- 格式為 "on xyz" 的事件:將處理器附加到事件 "xyz"
- 格式為 "as xyz" 的行為:附加名為 "xyz" 的行為
- 行為的屬性:設定行為屬性值
請勿直接呼叫此方法,因為它是一個 PHP 魔術方法,當執行 $component->property = $value;
時,它會被隱式地呼叫。
public void __set ( $name, $value ) | ||
$name | string |
屬性名稱或事件名稱 |
$value | mixed |
屬性值 |
throws | yii\base\UnknownPropertyException |
如果屬性未定義 |
---|---|---|
throws | yii\base\InvalidCallException |
如果屬性是唯讀的。 |
public function __set($name, $value)
{
if ($name === $this->filterAttributeName) {
$this->setFilter($value);
} else {
parent::__set($name, $value);
}
}
將組件屬性設定為 null。
此方法將依以下順序檢查並採取相應的動作
- setter 定義的屬性:將屬性值設定為 null
- 行為的屬性:將屬性值設定為 null
請勿直接呼叫此方法,因為它是一個 PHP 魔術方法,當執行 unset($component->property)
時,它會被隱式地呼叫。
public void __unset ( $name ) | ||
$name | string |
屬性名稱 |
throws | yii\base\InvalidCallException |
如果屬性是唯讀的。 |
---|
public function __unset($name)
{
if ($name === $this->filterAttributeName) {
$this->setFilter(null);
} else {
parent::__unset($name);
}
}
定義於: yii\base\Model::activeAttributes()
返回當前場景中需要驗證的屬性名稱。
public string[] activeAttributes ( ) | ||
return | string[] |
安全屬性名稱 |
---|
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 | string |
屬性名稱 |
$error | string |
新的錯誤訊息 |
public function addError($attribute, $error = '')
{
$this->_errors[$attribute][] = $error;
}
定義於: yii\base\Model::addErrors()
新增錯誤列表。
public array addErrors ( array $items ) | ||
$items | array |
錯誤列表。 陣列鍵必須是屬性名稱。 陣列值應為錯誤訊息。 如果一個屬性有多個錯誤,這些錯誤必須以陣列的形式給出。 您可以使用 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);
}
}
}
定義於: 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 | string |
行為的名稱。 |
$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 | array |
要附加到組件的行為列表 |
public function attachBehaviors($behaviors)
{
$this->ensureBehaviors();
foreach ($behaviors as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
定義於: yii\base\Model::attributeHints()
返回屬性提示。
屬性提示主要用於顯示目的。 例如,給定一個屬性 isPublic
,我們可以宣告一個提示 貼文是否應對未登入的使用者可見
,這提供了屬性含義的使用者友善描述,並且可以顯示給終端使用者。
與標籤不同,如果省略了明確宣告,則不會產生提示。
請注意,為了繼承父類別中定義的提示,子類別需要使用諸如 array_merge()
之類的函式將父提示與子提示合併。
public array attributeHints ( ) | ||
return | array |
屬性提示 (名稱 => 提示) |
---|
public function attributeHints()
{
return [];
}
返回屬性標籤。
屬性標籤主要用於顯示目的。 例如,給定一個屬性 firstName
,我們可以宣告一個標籤 名字
,它更使用者友善,並且可以顯示給終端使用者。
預設情況下,屬性標籤是使用 generateAttributeLabel() 產生的。 此方法允許您明確指定屬性標籤。
請注意,為了繼承父類別中定義的標籤,子類別需要使用諸如 array_merge()
之類的函式將父標籤與子標籤合併。
public array attributeLabels ( ) | ||
return | array |
屬性標籤 (名稱 => 標籤) |
---|
public function attributeLabels()
{
return [
$this->filterAttributeName => $this->filterAttributeLabel,
];
}
返回屬性名稱列表。
預設情況下,此方法回傳類別的所有 public 非靜態屬性。 您可以覆寫此方法來變更預設行為。
public string[] attributes ( ) | ||
return | string[] |
屬性名稱列表。 |
---|
public function attributes()
{
return [
$this->filterAttributeName,
];
}
定義於: 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 | array |
行為組態。 |
---|
public function behaviors()
{
return [];
}
從 $filter 值建立實際的過濾條件規範。
public mixed|false build ( $runValidation = true ) | ||
$runValidation | boolean |
是否在建構過濾器之前執行驗證(呼叫 validate())。 預設為 |
return | mixed|false |
建構的實際過濾器值,如果驗證失敗,則為 |
---|
public function build($runValidation = true)
{
if ($runValidation && !$this->validate()) {
return false;
}
return $this->buildInternal();
}
執行實際的過濾器建立。
預設情況下,此方法回傳 normalize() 的結果。 子類別可以覆寫此方法以提供更具體的實作。
protected mixed buildInternal ( ) | ||
return | mixed |
建構的實際過濾器值。 |
---|
protected function buildInternal()
{
return $this->normalize(false);
}
返回一個值,指示是否可以讀取屬性。
如果滿足以下條件,則可以讀取屬性
- 類別具有與指定名稱相關聯的 getter 方法(在這種情況下,屬性名稱不區分大小寫);
- 類別具有具有指定名稱的成員變數(當
$checkVars
為 true 時); - 附加的行為具有給定名稱的可讀屬性(當
$checkBehaviors
為 true 時)。
public boolean canGetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
屬性名稱 |
$checkVars | boolean |
是否將成員變數視為屬性 |
$checkBehaviors | boolean |
是否將行為的屬性視為此組件的屬性 |
return | boolean |
屬性是否可以讀取 |
---|
public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if ($name === $this->filterAttributeName) {
return true;
}
return parent::canGetProperty($name, $checkVars, $checkBehaviors);
}
返回一個值,指示是否可以設定屬性。
如果滿足以下條件,則可以寫入屬性
- 類別具有與指定名稱相關聯的 setter 方法(在這種情況下,屬性名稱不區分大小寫);
- 類別具有具有指定名稱的成員變數(當
$checkVars
為 true 時); - 附加的行為具有給定名稱的可寫屬性(當
$checkBehaviors
為 true 時)。
public boolean canSetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
屬性名稱 |
$checkVars | boolean |
是否將成員變數視為屬性 |
$checkBehaviors | boolean |
是否將行為的屬性視為此組件的屬性 |
return | boolean |
屬性是否可以寫入 |
---|
public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if ($name === $this->filterAttributeName) {
return true;
}
return parent::canSetProperty($name, $checkVars, $checkBehaviors);
}
::class
。
定義於: yii\base\BaseObject::className()
返回此類別的完整限定名稱。
public static string className ( ) | ||
return | string |
此類別的完整限定名稱。 |
---|
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;
}
返回 $errorMessages 的預設值。
protected array defaultErrorMessages ( ) | ||
return | array |
|
---|
protected function defaultErrorMessages()
{
return [
'invalidFilter' => Yii::t('yii', 'The format of {filter} is invalid.'),
'operatorRequireMultipleOperands' => Yii::t('yii', 'Operator "{operator}" requires multiple operands.'),
'unknownAttribute' => Yii::t('yii', 'Unknown filter attribute "{attribute}"'),
'invalidAttributeValueFormat' => Yii::t('yii', 'Condition for "{attribute}" should be either a value or valid operator specification.'),
'operatorRequireAttribute' => Yii::t('yii', 'Operator "{operator}" must be used with a search attribute.'),
'unsupportedOperatorType' => Yii::t('yii', '"{attribute}" does not support operator "{operator}".'),
];
}
public yii\base\Behavior|null detachBehavior ( $name ) | ||
$name | string |
行為的名稱。 |
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);
}
}
從給定的驗證器偵測屬性類型。
protected string|null detectSearchAttributeType ( yii\validators\Validator $validator ) | ||
$validator | yii\validators\Validator |
從中偵測屬性類型的驗證器。 |
return | string|null |
偵測到的屬性類型。 |
---|
protected function detectSearchAttributeType(Validator $validator)
{
if ($validator instanceof BooleanValidator) {
return self::TYPE_BOOLEAN;
}
if ($validator instanceof NumberValidator) {
return $validator->integerOnly ? self::TYPE_INTEGER : self::TYPE_FLOAT;
}
if ($validator instanceof StringValidator) {
return self::TYPE_STRING;
}
if ($validator instanceof EachValidator) {
return self::TYPE_ARRAY;
}
if ($validator instanceof DateValidator) {
if ($validator->type == DateValidator::TYPE_DATETIME) {
return self::TYPE_DATETIME;
}
if ($validator->type == DateValidator::TYPE_TIME) {
return self::TYPE_TIME;
}
return self::TYPE_DATE;
}
}
從 $searchModel 驗證規則組合 $searchAttributeTypes 的預設值。
protected array detectSearchAttributeTypes ( ) | ||
return | array |
屬性類型地圖。 |
---|
protected function detectSearchAttributeTypes()
{
$model = $this->getSearchModel();
$attributeTypes = [];
foreach ($model->activeAttributes() as $attribute) {
$attributeTypes[$attribute] = self::TYPE_STRING;
}
foreach ($model->getValidators() as $validator) {
$type = $this->detectSearchAttributeType($validator);
if ($type !== null) {
foreach ((array) $validator->attributes as $attribute) {
$attributeTypes[$attribute] = $type;
}
}
}
return $attributeTypes;
}
定義於: 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 | array |
可擴展的欄位名稱或欄位定義的列表。請參閱 fields() 以瞭解傳回值的格式。 |
---|
public function extraFields()
{
return [];
}
定義於: yii\base\ArrayableTrait::extractFieldsFor()
從給定根欄位的欄位集合中提取巢狀欄位。巢狀欄位以點 (.) 分隔。例如:"item.id" 前面的範例將提取 "id"。
protected array extractFieldsFor ( array $fields, $rootField ) | ||
$fields | array |
請求提取的欄位 |
$rootField | string |
我們想要提取巢狀欄位的根欄位 |
return | array |
為給定欄位提取的巢狀欄位 |
---|
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 | array |
請求提取的欄位 |
return | array |
從給定的巢狀欄位中提取的根欄位 |
---|
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 | array |
欄位名稱或欄位定義的列表。 |
---|
public function fields()
{
$fields = array_keys(Yii::getObjectVars($this));
return array_combine($fields, $fields);
}
在 $searchModel 的範圍內驗證屬性值,如果有的話,則應用屬性值過濾器。
protected mixed filterAttributeValue ( $attribute, $value ) | ||
$attribute | string |
屬性名稱。 |
$value | mixed |
屬性值。 |
return | mixed |
已篩選的屬性值。 |
---|
protected function filterAttributeValue($attribute, $value)
{
$model = $this->getSearchModel();
if (!$model->isAttributeSafe($attribute)) {
$this->addError($this->filterAttributeName, $this->parseErrorMessage('unknownAttribute', ['attribute' => $attribute]));
return $value;
}
$model->{$attribute} = $value;
if (!$model->validate([$attribute])) {
$this->addError($this->filterAttributeName, $model->getFirstError($attribute));
return $value;
}
return $model->{$attribute};
}
返回此模型類別應使用的表單名稱。
表單名稱主要由 yii\widgets\ActiveForm 用於決定如何命名模型中屬性的輸入欄位。如果表單名稱為 "A",而屬性名稱為 "b",則對應的輸入名稱將為 "A[b]"。如果表單名稱為空字串,則輸入名稱將為 "b"。
上述命名架構的目的是,對於包含多個不同模型的表單,每個模型的屬性都分組在 POST 資料的子陣列中,這樣更容易區分它們。
預設情況下,此方法會傳回模型類別名稱(不含命名空間部分)作為表單名稱。當模型用於不同的表單時,您可以覆寫它。
public string formName ( ) | ||
return | string |
此模型類別的表單名稱。 |
---|---|---|
throws | yii\base\InvalidConfigException |
當表單使用匿名類別定義且未覆寫 |
public function formName()
{
return '';
}
定義於: yii\base\Model::generateAttributeLabel()
根據給定的屬性名稱產生使用者友好的屬性標籤。
這是透過將底線、破折號和點替換為空格,並將每個單字的第一個字母更改為大寫來完成的。例如,'department_name' 或 'DepartmentName' 將產生 'Department Name'。
public string generateAttributeLabel ( $name ) | ||
$name | string |
欄位名稱 |
return | string |
屬性標籤 |
---|
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 | string |
屬性名稱 |
return | string |
屬性提示 |
---|
public function getAttributeHint($attribute)
{
$hints = $this->attributeHints();
return isset($hints[$attribute]) ? $hints[$attribute] : '';
}
public string getAttributeLabel ( $attribute ) | ||
$attribute | string |
屬性名稱 |
return | string |
屬性標籤 |
---|
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 | array |
不應傳回其值的屬性列表。 |
return | array |
屬性值 (name => value)。 |
---|
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 | string |
行為名稱 |
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 getErrorMessages ( ) | ||
return | array |
格式為 |
---|
public function getErrorMessages()
{
if (!is_array($this->_errorMessages)) {
if ($this->_errorMessages === null) {
$this->_errorMessages = $this->defaultErrorMessages();
} else {
$this->_errorMessages = array_merge(
$this->defaultErrorMessages(),
call_user_func($this->_errorMessages)
);
}
}
return $this->_errorMessages;
}
public array getErrorSummary ( $showAllErrors ) | ||
$showAllErrors | boolean |
布林值,如果設定為 true,則會顯示每個屬性的每個錯誤訊息,否則只會顯示每個屬性的第一個錯誤訊息。 |
return | array |
所有屬性的錯誤,以一維陣列形式呈現。如果沒有錯誤,則傳回空陣列。 |
---|
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 | array |
所有屬性或指定屬性的錯誤。如果沒有錯誤,則傳回空陣列。請參閱 getErrors() 以取得詳細說明。請注意,當傳回所有屬性的錯誤時,結果是一個二維陣列,如下所示
|
---|
public function getErrors($attribute = null)
{
if ($attribute === null) {
return $this->_errors === null ? [] : $this->_errors;
}
return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : [];
}
public mixed getFilter ( ) | ||
return | mixed |
原始過濾器值。 |
---|
public function getFilter()
{
return $this->_filter;
}
public string|null getFirstError ( $attribute ) | ||
$attribute | string |
屬性名稱。 |
return | string|null |
錯誤訊息。如果沒有錯誤,則傳回 Null。 |
---|
public function getFirstError($attribute)
{
return isset($this->_errors[$attribute]) ? reset($this->_errors[$attribute]) : null;
}
public array getFirstErrors ( ) | ||
return | array |
第一個錯誤。陣列鍵是屬性名稱,而陣列值是對應的錯誤訊息。如果沒有錯誤,則會傳回空陣列。 |
---|
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 | string |
此模型所處的情境。預設為 SCENARIO_DEFAULT。 |
---|
public function getScenario()
{
return $this->_scenario;
}
public array getSearchAttributeTypes ( ) | ||
return | array |
搜尋屬性類型映射。 |
---|
public function getSearchAttributeTypes()
{
if ($this->_searchAttributeTypes === null) {
$this->_searchAttributeTypes = $this->detectSearchAttributeTypes();
}
return $this->_searchAttributeTypes;
}
public yii\base\Model getSearchModel ( ) | ||
return | yii\base\Model |
模型實例。 |
---|---|---|
throws | yii\base\InvalidConfigException |
在無效的組態上。 |
public function getSearchModel()
{
if (!is_object($this->_searchModel) || $this->_searchModel instanceof \Closure) {
$model = Yii::createObject($this->_searchModel);
if (!$model instanceof Model) {
throw new InvalidConfigException('`' . get_class($this) . '::$searchModel` should be an instance of `' . Model::className() . '` or its DI compatible configuration.');
}
$this->_searchModel = $model;
}
return $this->_searchModel;
}
定義於: 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;
}
定義於: 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 | string |
事件名稱 |
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 | string |
屬性名稱 |
$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 | string |
屬性名稱 |
$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()
返回靜態類別實例,可用於獲取元資訊。
public static static instance ( $refresh = false ) | ||
$refresh | boolean |
是否重新建立靜態實例,即使它已經被快取。 |
return | yii\data\DataFilter |
類別實例。 |
---|
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 | string |
屬性名稱 |
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 | string |
屬性名稱 |
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 | string |
屬性名稱 |
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 | array |
要載入的資料陣列,通常為 |
$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 | array |
要填充的模型。請注意,所有模型應具有相同的類別。 |
$data | array |
資料陣列。這通常是 |
$formName | string|null |
$formName |
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;
}
標準化過濾器值,根據 $filterControls 和 $attributeMap 替換原始鍵。
public array|boolean normalize ( $runValidation = true ) | ||
$runValidation | boolean |
是否在正規化篩選器之前執行驗證 (調用 validate())。預設為 |
return | array|boolean |
正規化的篩選器值,如果驗證失敗則為 |
---|
public function normalize($runValidation = true)
{
if ($runValidation && !$this->validate()) {
return false;
}
$filter = $this->getFilter();
if (!is_array($filter) || empty($filter)) {
return [];
}
return $this->normalizeComplexFilter($filter);
}
定義於: yii\base\Component::off()
從此組件中分離現有的事件處理程序。
此方法與 on() 相反。
注意:如果為事件名稱傳遞了萬用字元模式,則只會移除使用此萬用字元註冊的處理常式,而使用符合此萬用字元的純名稱註冊的處理常式將保留。
另請參閱 on()。
public boolean off ( $name, $handler = null ) | ||
$name | string |
事件名稱 |
$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 | string |
要檢查的偏移量。 |
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 | string |
要檢索元素的偏移量。 |
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 | string |
要設定元素的偏移量 |
$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 | string |
要取消設定元素的偏移量 |
#[\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 | string |
事件名稱 |
$handler | 可調用 (callable) |
事件處理常式 |
$data | mixed |
事件觸發時要傳遞給事件處理常式的資料。當調用事件處理常式時,可以透過 yii\base\Event::$data 存取此資料。 |
$append | boolean |
是否將新的事件處理常式附加到現有處理常式列表的末尾。如果為 false,則新的處理常式將插入到現有處理常式列表的開頭。 |
public function on($name, $handler, $data = null, $append = true)
{
$this->ensureBehaviors();
if (strpos($name, '*') !== false) {
if ($append || empty($this->_eventWildcards[$name])) {
$this->_eventWildcards[$name][] = [$handler, $data];
} else {
array_unshift($this->_eventWildcards[$name], [$handler, $data]);
}
return;
}
if ($append || empty($this->_events[$name])) {
$this->_events[$name][] = [$handler, $data];
} else {
array_unshift($this->_events[$name], [$handler, $data]);
}
}
public void onUnsafeAttribute ( $name, $value ) | ||
$name | string |
不安全的屬性名稱 |
$value | mixed |
屬性值 |
public function onUnsafeAttribute($name, $value)
{
if (YII_DEBUG) {
Yii::debug("Failed to set unsafe attribute '$name' in '" . get_class($this) . "'.", __METHOD__);
}
}
從 $errorMessages 解析訊息內容,由訊息鍵指定。
protected string parseErrorMessage ( $messageKey, $params = [] ) | ||
$messageKey | string |
訊息鍵。 |
$params | array |
要解析到訊息中的參數。 |
return | string |
組成的訊息字串。 |
---|
protected function parseErrorMessage($messageKey, $params = [])
{
$messages = $this->getErrorMessages();
if (isset($messages[$messageKey])) {
$message = $messages[$messageKey];
} else {
$message = Yii::t('yii', 'The format of {filter} is invalid.');
}
$params = array_merge(
[
'filter' => $this->getAttributeLabel($this->filterAttributeName),
],
$params
);
return Yii::$app->getI18n()->format($message, $params, Yii::$app->language);
}
定義於: yii\base\ArrayableTrait::resolveFields()
確定哪些欄位可以由 toArray() 返回。
此方法將首先從給定的欄位中提取根欄位。然後,它將根據 fields() 和 extraFields() 中宣告的根欄位檢查請求的根欄位,以確定可以返回哪些欄位。
protected array resolveFields ( array $fields, array $expand ) | ||
$fields | array |
正在請求匯出的欄位 |
$expand | array |
正在請求匯出的額外欄位 |
return | array |
要匯出的欄位列表。陣列鍵是欄位名稱,陣列值是對應的物件屬性名稱或返回欄位值的 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()
之類的函式將父規則與子規則合併。
public array rules ( ) | ||
return | array |
驗證規則 |
---|
public function rules()
{
return [
[$this->filterAttributeName, 'validateFilter', 'skipOnEmpty' => false],
];
}
定義於: yii\base\Model::safeAttributes()
返回在當前場景中可以大量指派的安全屬性名稱。
public string[] safeAttributes ( ) | ||
return | string[] |
安全屬性名稱 |
---|
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 | array |
情境列表和對應的活動屬性。 |
---|
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 void setAttributes ( $values, $safeOnly = true ) | ||
$values | array |
要賦值給模型的屬性值 (名稱 => 值)。 |
$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);
}
}
}
}
設定回應無效過濾器結構的錯誤訊息列表,格式為:[errorKey => message]
。
訊息可能包含佔位符,這些佔位符將根據訊息上下文填充。對於每個訊息,都有一個 {filter}
佔位符可用,它引用 $filterAttributeName 屬性的標籤。
public void setErrorMessages ( $errorMessages ) | ||
$errorMessages | array|Closure |
錯誤訊息格式為 |
public function setErrorMessages($errorMessages)
{
if (is_array($errorMessages)) {
$errorMessages = array_merge($this->defaultErrorMessages(), $errorMessages);
}
$this->_errorMessages = $errorMessages;
}
public void setFilter ( $filter ) | ||
$filter | mixed |
原始過濾器值。 |
public function setFilter($filter)
{
$this->_filter = $filter;
}
public void setScenario ( $value ) | ||
$value | string |
此模型所處的場景。 |
public function setScenario($value)
{
$this->_scenario = $value;
}
public void setSearchAttributeTypes ( $searchAttributeTypes ) | ||
$searchAttributeTypes | array|null |
搜尋屬性類型映射。 |
public function setSearchAttributeTypes($searchAttributeTypes)
{
$this->_searchAttributeTypes = $searchAttributeTypes;
}
public void setSearchModel ( $model ) | ||
$model | yii\base\Model|array|string|callable |
模型實例或其相容於 DI 的設定。 |
throws | yii\base\InvalidConfigException |
在無效的組態上。 |
---|
public function setSearchModel($model)
{
if (is_object($model) && !$model instanceof Model && !$model instanceof \Closure) {
throw new InvalidConfigException('`' . get_class($this) . '::$searchModel` should be an instance of `' . Model::className() . '` or its DI compatible configuration.');
}
$this->_searchModel = $model;
}
定義於: 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 | array |
請求的欄位。如果為空或包含 '*',則會傳回 fields() 指定的所有欄位。欄位可以是巢狀的,用點 (.) 分隔。例如:item.field.sub-field。 |
$expand | array |
請求用於匯出的額外欄位。只會考慮在 extraFields() 中宣告的欄位。Expand 也可以是巢狀的,用點 (.) 分隔。例如:item.expand1.expand2。 |
$recursive | boolean |
是否以遞迴方式回傳嵌入物件的陣列表示。 |
return | array |
物件的陣列表示 |
---|
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 | 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);
}
定義於: 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();
}
驗證特定屬性的搜尋條件。
protected void validateAttributeCondition ( $attribute, $condition ) | ||
$attribute | string |
搜尋屬性名稱。 |
$condition | mixed |
搜尋條件。 |
protected function validateAttributeCondition($attribute, $condition)
{
$attributeTypes = $this->getSearchAttributeTypes();
if (!isset($attributeTypes[$attribute])) {
$this->addError($this->filterAttributeName, $this->parseErrorMessage('unknownAttribute', ['attribute' => $attribute]));
return;
}
if (is_array($condition)) {
$operatorCount = 0;
foreach ($condition as $rawOperator => $value) {
if (isset($this->filterControls[$rawOperator])) {
$operator = $this->filterControls[$rawOperator];
if (isset($this->operatorTypes[$operator])) {
$operatorCount++;
$this->validateOperatorCondition($rawOperator, $value, $attribute);
}
}
}
if ($operatorCount > 0) {
if ($operatorCount < count($condition)) {
$this->addError($this->filterAttributeName, $this->parseErrorMessage('invalidAttributeValueFormat', ['attribute' => $attribute]));
}
} else {
// attribute may allow array value:
$this->validateAttributeValue($attribute, $condition);
}
} else {
$this->validateAttributeValue($attribute, $condition);
}
}
在 model 的範圍內驗證屬性值。
protected void validateAttributeValue ( $attribute, $value ) | ||
$attribute | string |
屬性名稱。 |
$value | mixed |
屬性值。 |
protected function validateAttributeValue($attribute, $value)
{
$model = $this->getSearchModel();
if (!$model->isAttributeSafe($attribute)) {
$this->addError($this->filterAttributeName, $this->parseErrorMessage('unknownAttribute', ['attribute' => $attribute]));
return;
}
$model->{$attribute} = $value === $this->nullValue ? null : $value;
if (!$model->validate([$attribute])) {
$this->addError($this->filterAttributeName, $model->getFirstError($attribute));
return;
}
}
驗證由單個條件組成的區塊條件。
這涵蓋了諸如 not
之類的運算子。
protected void validateBlockCondition ( $operator, $condition ) | ||
$operator | string |
原始運算子控制關鍵字。 |
$condition | mixed |
原始條件。 |
protected function validateBlockCondition($operator, $condition)
{
$this->validateCondition($condition);
}
驗證過濾條件。
protected void validateCondition ( $condition ) | ||
$condition | mixed |
原始篩選條件。 |
protected function validateCondition($condition)
{
if (!is_array($condition)) {
$this->addError($this->filterAttributeName, $this->parseErrorMessage('invalidFilter'));
return;
}
if (empty($condition)) {
return;
}
foreach ($condition as $key => $value) {
$method = 'validateAttributeCondition';
if (isset($this->filterControls[$key])) {
$controlKey = $this->filterControls[$key];
if (isset($this->conditionValidators[$controlKey])) {
$method = $this->conditionValidators[$controlKey];
}
}
$this->$method($key, $value);
}
}
驗證由多個獨立條件組成的合取條件。
這涵蓋了諸如 and
和 or
之類的運算子。
protected void validateConjunctionCondition ( $operator, $condition ) | ||
$operator | string |
原始運算子控制關鍵字。 |
$condition | mixed |
原始條件。 |
protected function validateConjunctionCondition($operator, $condition)
{
if (!is_array($condition) || !ArrayHelper::isIndexed($condition)) {
$this->addError($this->filterAttributeName, $this->parseErrorMessage('operatorRequireMultipleOperands', ['operator' => $operator]));
return;
}
foreach ($condition as $part) {
$this->validateCondition($part);
}
}
驗證過濾器屬性值以符合過濾條件規範。
public void validateFilter ( ) |
public function validateFilter()
{
$value = $this->getFilter();
if ($value !== null) {
$this->validateCondition($value);
}
}
public static boolean validateMultiple ( $models, $attributeNames = null ) | ||
$models | array |
要驗證的模型 |
$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;
}
驗證運算符條件。
protected void validateOperatorCondition ( $operator, $condition, $attribute = null ) | ||
$operator | string |
原始運算子控制關鍵字。 |
$condition | mixed |
屬性條件。 |
$attribute | string|null |
屬性名稱。 |
protected function validateOperatorCondition($operator, $condition, $attribute = null)
{
if ($attribute === null) {
// absence of an attribute indicates that operator has been placed in a wrong position
$this->addError($this->filterAttributeName, $this->parseErrorMessage('operatorRequireAttribute', ['operator' => $operator]));
return;
}
$internalOperator = $this->filterControls[$operator];
// check operator type :
$operatorTypes = $this->operatorTypes[$internalOperator];
if ($operatorTypes !== '*') {
$attributeTypes = $this->getSearchAttributeTypes();
$attributeType = $attributeTypes[$attribute];
if (!in_array($attributeType, $operatorTypes, true)) {
$this->addError($this->filterAttributeName, $this->parseErrorMessage('unsupportedOperatorType', ['attribute' => $attribute, 'operator' => $operator]));
return;
}
}
if (in_array($internalOperator, $this->multiValueOperators, true)) {
// multi-value operator:
if (!is_array($condition)) {
$this->addError($this->filterAttributeName, $this->parseErrorMessage('operatorRequireMultipleOperands', ['operator' => $operator]));
} else {
foreach ($condition as $v) {
$this->validateAttributeValue($attribute, $v);
}
}
} else {
// single-value operator :
$this->validateAttributeValue($attribute, $condition);
}
}
註冊 或 登入 以發表評論。