類別 yii\data\ActiveDataFilter
ActiveDataFilter 允許組合過濾條件,格式適用於 yii\db\QueryInterface::where()。
另請參閱 yii\data\DataFilter。
公開屬性
公開方法
Protected Methods
Events
Event | 類型 | 描述 | 定義於 |
---|---|---|---|
EVENT_AFTER_VALIDATE | yii\base\Event | 在 validate() 結束時引發的事件 | yii\base\Model |
EVENT_BEFORE_VALIDATE | yii\base\ModelEvent | 在 validate() 開始時引發的事件。 | yii\base\Model |
Constants
Constant | Value | 描述 | 定義於 |
---|---|---|---|
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 |
Property Details
將篩選條件關鍵字對應到建立方法。這些方法由 buildCondition() 用於建立實際的篩選條件。可以使用 PHP 回呼指定特定的條件建立器。例如
[
'XOR' => function (string $operator, mixed $condition) {
//return array;
},
'LIKE' => function (string $operator, mixed $condition, string $attribute) {
//return array;
},
]
'AND' => 'buildConjunctionCondition',
'OR' => 'buildConjunctionCondition',
'NOT' => 'buildBlockCondition',
'<' => 'buildOperatorCondition',
'>' => 'buildOperatorCondition',
'<=' => 'buildOperatorCondition',
'>=' => 'buildOperatorCondition',
'=' => 'buildOperatorCondition',
'!=' => 'buildOperatorCondition',
'IN' => 'buildOperatorCondition',
'NOT IN' => 'buildOperatorCondition',
'LIKE' => 'buildOperatorCondition',
]
將篩選運算子對應到 yii\db\QueryInterface::where() 中使用的運算子。格式為:[filterOperator => queryOperator]
。如果特定運算子關鍵字未出現在對應表中,將會直接使用它。
通常可以將對應表留空,因為篩選運算子名稱與 yii\db\QueryInterface::where() 中使用的名稱一致。但是,在某些特殊情況下,您可能需要調整它。例如,當使用 PostgreSQL 時,您可能想要設定以下對應
[
'LIKE' => 'ILIKE'
]
Method Details
定義於: yii\base\Component::__call()
呼叫指定的非類別方法。
此方法將檢查是否有任何附加的行為具有指定的名稱方法,如果有的話,將會執行它。
請勿直接呼叫此方法,因為它是 PHP 魔術方法,當呼叫未知方法時會隱式呼叫它。
public mixed __call ( $name, $params ) | ||
$name | 字串 |
方法名稱 |
$params | 陣列 |
方法參數 |
return | 混合 |
方法傳回值 |
---|---|---|
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 | 陣列 |
將用於初始化物件屬性的名稱-值對 |
public function __construct($config = [])
{
if (!empty($config)) {
Yii::configure($this, $config);
}
$this->init();
}
定義於: yii\data\DataFilter::__get()
傳回元件屬性的值。
此方法將依以下順序檢查並採取相應的動作
- 由 getter 定義的屬性:傳回 getter 結果
- 行為的屬性:傳回行為屬性值
請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 $value = $component->property;
時會隱式呼叫它。
public mixed __get ( $name ) | ||
$name | 字串 |
屬性名稱 |
return | 混合 |
屬性值或行為屬性的值 |
---|---|---|
throws | yii\base\UnknownPropertyException |
如果未定義屬性 |
throws | yii\base\InvalidCallException |
如果屬性為唯寫。 |
public function __get($name)
{
if ($name === $this->filterAttributeName) {
return $this->getFilter();
}
return parent::__get($name);
}
定義於: yii\data\DataFilter::__isset()
檢查屬性是否已設定,即已定義且非 null。
此方法將依以下順序檢查並採取相應的動作
- 由 setter 定義的屬性:傳回是否已設定屬性
- 行為的屬性:傳回是否已設定屬性
- 對於不存在的屬性傳回
false
請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 isset($component->property)
時會隱式呼叫它。
public boolean __isset ( $name ) | ||
$name | 字串 |
屬性名稱或事件名稱 |
return | boolean |
名稱屬性是否已設定 |
---|
public function __isset($name)
{
if ($name === $this->filterAttributeName) {
return $this->getFilter() !== null;
}
return parent::__isset($name);
}
定義於: yii\data\DataFilter::__set()
設定元件屬性的值。
此方法將依以下順序檢查並採取相應的動作
- 由 setter 定義的屬性:設定屬性值
- 格式為 "on xyz" 的事件:將處理常式附加到事件 "xyz"
- 格式為 "as xyz" 的行為:附加名為 "xyz" 的行為
- 行為的屬性:設定行為屬性值
請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 $component->property = $value;
時會隱式呼叫它。
public void __set ( $name, $value ) | ||
$name | 字串 |
屬性名稱或事件名稱 |
$value | 混合 |
屬性值 |
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);
}
}
定義於: yii\data\DataFilter::__unset()
將元件屬性設定為 null。
此方法將依以下順序檢查並採取相應的動作
- 由 setter 定義的屬性:將屬性值設定為 null
- 行為的屬性:將屬性值設定為 null
請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 unset($component->property)
時會隱式呼叫它。
public void __unset ( $name ) | ||
$name | 字串 |
屬性名稱 |
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 | 字串[] |
安全的屬性名稱 |
---|
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);
}
}
}
定義於: 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 [];
}
Defined in: yii\data\DataFilter::attributeLabels()
傳回屬性標籤。
屬性標籤主要用於顯示目的。例如,給定一個屬性 firstName
,我們可以宣告一個標籤 First Name
,使其更方便使用者閱讀,並可顯示給終端使用者。
預設情況下,屬性標籤是使用 generateAttributeLabel() 產生的。此方法允許您明確指定屬性標籤。
請注意,為了繼承父類別中定義的標籤,子類別需要使用諸如 array_merge()
之類的函數將父標籤與子標籤合併。
public array attributeLabels ( ) | ||
return | 陣列 |
屬性標籤 (名稱 => 標籤) |
---|
public function attributeLabels()
{
return [
$this->filterAttributeName => $this->filterAttributeLabel,
];
}
public string[] attributes ( ) | ||
return | 字串[] |
屬性名稱列表。 |
---|
public function attributes()
{
return [
$this->filterAttributeName,
];
}
Defined in: 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;
}
Defined in: yii\base\Component::behaviors()
傳回此元件應表現為的行為列表。
子類別可以覆寫此方法,以指定它們想要表現為的行為。
此方法的傳回值應該是由行為名稱索引的行為物件或組態陣列。行為組態可以是指定行為類別的字串,也可以是具有以下結構的陣列
'behaviorName' => [
'class' => 'BehaviorClass',
'property1' => 'value1',
'property2' => 'value2',
]
請注意,行為類別必須從 yii\base\Behavior 擴展。行為可以使用名稱或匿名方式附加。當名稱用作陣列索引鍵時,使用此名稱,稍後可以使用 getBehavior() 檢索行為,或使用 detachBehavior() 分離行為。匿名行為無法檢索或分離。
在此方法中宣告的行為將自動(按需)附加到元件。
public array behaviors ( ) | ||
return | 陣列 |
行為組態。 |
---|
public function behaviors()
{
return [];
}
Defined in: yii\data\DataFilter::build()
根據 $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();
}
為特定屬性建立搜尋條件。
protected array buildAttributeCondition ( $attribute, $condition ) | ||
$attribute | 字串 |
搜尋屬性名稱。 |
$condition | 混合 |
搜尋條件。 |
return | 陣列 |
實際條件。 |
---|
protected function buildAttributeCondition($attribute, $condition)
{
if (is_array($condition)) {
$parts = [];
foreach ($condition as $operator => $value) {
if (isset($this->operatorTypes[$operator])) {
if (isset($this->conditionBuilders[$operator])) {
$method = $this->conditionBuilders[$operator];
if (is_string($method)) {
$callback = [$this, $method];
} else {
$callback = $method;
}
$parts[] = $callback($operator, $value, $attribute);
} else {
$parts[] = $this->buildOperatorCondition($operator, $value, $attribute);
}
}
}
if (!empty($parts)) {
if (count($parts) > 1) {
return array_merge(['AND'], $parts);
}
return array_shift($parts);
}
}
return [$attribute => $this->filterAttributeValue($attribute, $condition)];
}
建立區塊條件,該條件由單一條件組成。
它涵蓋諸如 not
之類的運算子。
protected array buildBlockCondition ( $operator, $condition ) | ||
$operator | 字串 |
運算子關鍵字。 |
$condition | 混合 |
原始條件。 |
return | 陣列 |
實際條件。 |
---|
protected function buildBlockCondition($operator, $condition)
{
if (isset($this->queryOperatorMap[$operator])) {
$operator = $this->queryOperatorMap[$operator];
}
return [
$operator,
$this->buildCondition($condition),
];
}
protected array buildCondition ( $condition ) | ||
$condition | 陣列 | |
return | 陣列 |
已建置的條件。 |
---|
protected function buildCondition($condition)
{
$parts = [];
foreach ($condition as $key => $value) {
if (isset($this->conditionBuilders[$key])) {
$method = $this->conditionBuilders[$key];
if (is_string($method)) {
$callback = [$this, $method];
} else {
$callback = $method;
}
} else {
$callback = [$this, 'buildAttributeCondition'];
}
$parts[] = $callback($key, $value);
}
if (!empty($parts)) {
if (count($parts) > 1) {
array_unshift($parts, 'AND');
} else {
$parts = array_shift($parts);
}
}
return $parts;
}
建立連詞條件,該條件由多個獨立條件組成。
它涵蓋諸如 and
和 or
之類的運算子。
protected array buildConjunctionCondition ( $operator, $condition ) | ||
$operator | 字串 |
運算子關鍵字。 |
$condition | 混合 |
原始條件。 |
return | 陣列 |
實際條件。 |
---|
protected function buildConjunctionCondition($operator, $condition)
{
if (isset($this->queryOperatorMap[$operator])) {
$operator = $this->queryOperatorMap[$operator];
}
$result = [$operator];
foreach ($condition as $part) {
$result[] = $this->buildCondition($part);
}
return $result;
}
執行實際的篩選器建立。
預設情況下,此方法傳回 normalize() 的結果。子類別可以覆寫此方法,以提供更具體的實作。
protected mixed buildInternal ( ) | ||
return | 混合 |
已建置的實際篩選器值。 |
---|
protected function buildInternal()
{
$filter = $this->normalize(false);
if (empty($filter)) {
return [];
}
return $this->buildCondition($filter);
}
建立運算子條件。
protected array buildOperatorCondition ( $operator, $condition, $attribute ) | ||
$operator | 字串 |
運算子關鍵字。 |
$condition | 混合 |
屬性條件。 |
$attribute | 字串 |
屬性名稱。 |
return | 陣列 |
實際條件。 |
---|
protected function buildOperatorCondition($operator, $condition, $attribute)
{
if (isset($this->queryOperatorMap[$operator])) {
$operator = $this->queryOperatorMap[$operator];
}
return [$operator, $attribute, $this->filterAttributeValue($attribute, $condition)];
}
Defined in: yii\data\DataFilter::canGetProperty()
傳回一個值,指出是否可以讀取屬性。
如果符合以下條件,則可以讀取屬性
- 類別具有與指定名稱關聯的 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)
{
if ($name === $this->filterAttributeName) {
return true;
}
return parent::canGetProperty($name, $checkVars, $checkBehaviors);
}
Defined in: yii\data\DataFilter::canSetProperty()
傳回一個值,指出是否可以設定屬性。
如果符合以下條件,則可以寫入屬性
- 類別具有與指定名稱關聯的 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)
{
if ($name === $this->filterAttributeName) {
return true;
}
return parent::canSetProperty($name, $checkVars, $checkBehaviors);
}
::class
。
Defined in: yii\base\BaseObject::className()
傳回此類別的完整限定名稱。
public static string className ( ) | ||
return | 字串 |
此類別的完整限定名稱。 |
---|
public static function className()
{
return get_called_class();
}
Defined in: 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]);
}
}
Defined in: 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;
}
Defined in: yii\data\DataFilter::defaultErrorMessages()
傳回 $errorMessages 的預設值。
protected array defaultErrorMessages ( ) | ||
return | 陣列 |
|
---|
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 | 字串 |
行為的名稱。 |
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;
}
Defined in: yii\base\Component::detachBehaviors()
從元件中分離所有行為。
public void detachBehaviors ( ) |
public function detachBehaviors()
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $name => $behavior) {
$this->detachBehavior($name);
}
}
Defined in: yii\data\DataFilter::detectSearchAttributeType()
從給定的驗證器偵測屬性類型。
protected yii\validators\Validator 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;
}
}
Defined in: yii\data\DataFilter::detectSearchAttributeTypes()
從 $searchModel 驗證規則組合 $searchAttributeTypes 的預設值。
protected array detectSearchAttributeTypes ( ) | ||
return | 陣列 |
屬性類型對應表。 |
---|
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;
}
Defined in: 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);
}
}
}
Defined in: yii\base\ArrayableTrait::extraFields()
傳回可以進一步展開並由 toArray() 傳回的欄位列表。
此方法與 fields() 類似,不同之處在於此方法傳回的欄位清單預設不會由 toArray() 傳回。只有在呼叫 toArray() 時明確指定要擴展的欄位名稱時,它們的值才會匯出。
預設實作傳回空陣列。
您可以覆寫此方法,以根據某些上下文資訊(例如,目前應用程式使用者)傳回可擴展欄位的清單。
另請參閱
public array extraFields ( ) | ||
return | 陣列 |
可擴展欄位名稱或欄位定義的清單。請參閱 fields() 以瞭解傳回值的格式。 |
---|
public function extraFields()
{
return [];
}
Defined in: 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);
}
Defined in: 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);
}
Defined in: 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);
}
Defined in: yii\data\DataFilter::filterAttributeValue()
在 $searchModel 的範圍內驗證屬性值,如果有的話,套用屬性值篩選器。
protected mixed filterAttributeValue ( $attribute, $value ) | ||
$attribute | 字串 |
屬性名稱。 |
$value | 混合 |
屬性值。 |
return | 混合 |
已篩選的屬性值。 |
---|
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};
}
Defined in: yii\data\DataFilter::formName()
傳回此模型類別應使用的表單名稱。
表單名稱主要由 yii\widgets\ActiveForm 用於判斷如何命名模型中屬性的輸入欄位。如果表單名稱為 "A" 且屬性名稱為 "b",則對應的輸入名稱將為 "A[b]"。如果表單名稱為空字串,則輸入名稱將為 "b"。
上述命名架構的目的是,對於包含多個不同模型的表單,每個模型的屬性都分組在 POST 資料的子陣列中,並且更容易區分它們。
預設情況下,此方法會傳回模型類別名稱(不含命名空間部分)作為表單名稱。當模型用於不同表單時,您可以覆寫它。
public string formName ( ) | ||
return | 字串 |
此模型類別的表單名稱。 |
---|---|---|
throws | yii\base\InvalidConfigException |
當表單是使用匿名類別定義,且未覆寫 |
public function formName()
{
return '';
}
Defined in: yii\base\Model::generateAttributeLabel()
根據給定的屬性名稱產生使用者友善的屬性標籤。
這是透過將底線、破折號和點號替換為空格,並將每個單字的首字母更改為大寫來完成的。例如,'department_name' 或 'DepartmentName' 將產生 'Department Name'。
public string generateAttributeLabel ( $name ) | ||
$name | 字串 |
欄位名稱 |
return | 字串 |
屬性標籤 |
---|
public function generateAttributeLabel($name)
{
return Inflector::camel2words($name, true);
}
Defined in: 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 | 陣列 |
屬性值 (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 | 字串 |
行為名稱 |
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 | 陣列 |
錯誤訊息,格式為 |
---|
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 | 陣列 |
所有屬性的錯誤,以一維陣列形式呈現。如果沒有錯誤,則回傳空陣列。 |
---|
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 mixed getFilter ( ) | ||
return | 混合 |
原始過濾器值。 |
---|
public function getFilter()
{
return $this->_filter;
}
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;
}
public array getSearchAttributeTypes ( ) | ||
return | 陣列 |
搜尋屬性類型映射。 |
---|
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 | 字串 |
事件名稱 |
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\data\ActiveDataFilter |
類別實例。 |
---|
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\data\DataFilter::normalize()
正規化篩選器值,根據 $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 | 字串 |
事件名稱 |
$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 | 混合 |
偏移量處的元素,如果在偏移量處未找到元素則為 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 | 混合 |
元素的值 |
#[\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 | 混合 |
當事件被觸發時,要傳遞給事件處理器的資料。當事件處理器被調用時,可以透過 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 | 混合 |
屬性值 |
public function onUnsafeAttribute($name, $value)
{
if (YII_DEBUG) {
Yii::debug("Failed to set unsafe attribute '$name' in '" . get_class($this) . "'.", __METHOD__);
}
}
定義於: yii\data\DataFilter::parseErrorMessage()
從訊息金鑰指定的 $errorMessages 中解析訊息內容。
protected string parseErrorMessage ( $messageKey, $params = [] ) | ||
$messageKey | 字串 |
訊息鍵。 |
$params | 陣列 |
要解析到訊息中的參數。 |
return | 字串 |
組成的訊息字串。 |
---|
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 | 陣列 |
正在請求導出的欄位 |
$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;
}
定義於: yii\data\DataFilter::rules()
傳回屬性的驗證規則。
驗證規則被 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 | 陣列 |
驗證規則 |
---|
public function rules()
{
return [
[$this->filterAttributeName, 'validateFilter', 'skipOnEmpty' => false],
];
}
定義於: 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 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);
}
}
}
}
定義於: yii\data\DataFilter::setErrorMessages()
設定回應無效篩選器結構的錯誤訊息列表,格式為:[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 | 混合 |
原始過濾器值。 |
public function setFilter($filter)
{
$this->_filter = $filter;
}
public void setScenario ( $value ) | ||
$value | 字串 |
此模型所處的場景。 |
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 | 陣列 |
正在請求的欄位。如果為空或包含 '*',則將回傳 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);
}
定義於: 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();
}
定義於: yii\data\DataFilter::validateAttributeCondition()
驗證特定屬性的搜尋條件。
protected void validateAttributeCondition ( $attribute, $condition ) | ||
$attribute | 字串 |
搜尋屬性名稱。 |
$condition | 混合 |
搜尋條件。 |
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);
}
}
定義於: yii\data\DataFilter::validateAttributeValue()
在模型的範圍內驗證屬性值。
protected void validateAttributeValue ( $attribute, $value ) | ||
$attribute | 字串 |
屬性名稱。 |
$value | 混合 |
屬性值。 |
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;
}
}
protected void validateBlockCondition ( $operator, $condition ) | ||
$operator | 字串 |
原始運算符控制關鍵字。 |
$condition | 混合 |
原始條件。 |
protected function validateBlockCondition($operator, $condition)
{
$this->validateCondition($condition);
}
定義於: yii\data\DataFilter::validateCondition()
驗證篩選器條件。
protected void validateCondition ( $condition ) | ||
$condition | 混合 |
原始篩選條件。 |
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);
}
}
protected void validateConjunctionCondition ( $operator, $condition ) | ||
$operator | 字串 |
原始運算符控制關鍵字。 |
$condition | 混合 |
原始條件。 |
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);
}
}
Defined in: yii\data\DataFilter::validateFilter()
驗證篩選器屬性值是否符合篩選器條件規範。
public void validateFilter ( ) |
public function validateFilter()
{
$value = $this->getFilter();
if ($value !== null) {
$this->validateCondition($value);
}
}
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;
}
Defined in: yii\data\DataFilter::validateOperatorCondition()
驗證運算子條件。
protected void validateOperatorCondition ( $operator, $condition, $attribute = null ) | ||
$operator | 字串 |
原始運算符控制關鍵字。 |
$condition | 混合 |
屬性條件。 |
$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);
}
}
註冊 或 登入 以發表評論。