1 位追蹤者

類別 yii\behaviors\AttributeBehavior

繼承關係yii\behaviors\AttributeBehavior » yii\base\Behavior » yii\base\BaseObject
實作介面yii\base\Configurable
子類別yii\behaviors\BlameableBehavior, yii\behaviors\OptimisticLockBehavior, yii\behaviors\SluggableBehavior, yii\behaviors\TimestampBehavior
自版本起可用2.0
原始碼 https://github.com/yiisoft/yii2/blob/master/framework/behaviors/AttributeBehavior.php

AttributeBehavior 會在特定事件發生時,自動將指定的值指派給 ActiveRecord 物件的一個或多個屬性。

若要使用 AttributeBehavior,請設定 $attributes 屬性,此屬性應指定需要更新的屬性列表,以及應觸發更新的對應事件。然後使用 PHP 可呼叫物件設定 $value 屬性,其回傳值將用於指派給目前的屬性。例如:

use yii\behaviors\AttributeBehavior;

public function behaviors()
{
    return [
        [
            'class' => AttributeBehavior::class,
            'attributes' => [
                ActiveRecord::EVENT_BEFORE_INSERT => 'attribute1',
                ActiveRecord::EVENT_BEFORE_UPDATE => 'attribute2',
            ],
            'value' => function ($event) {
                return 'some value';
            },
        ],
    ];
}

由於屬性值將由此行為自動設定,因此它們通常不是使用者輸入,因此不應驗證,即它們不應出現在模型的 rules() 方法中。

公開屬性

隱藏繼承的屬性

屬性 類型 描述 定義於
$attributes 陣列 要自動填入透過 $value 指定之值的屬性列表。 yii\behaviors\AttributeBehavior
$owner yii\base\Component|null 此行為的擁有者 yii\base\Behavior
$preserveNonEmptyValues 布林值 是否保留非空的屬性值。 yii\behaviors\AttributeBehavior
$skipUpdateOnClean 布林值 $owner 未被修改時,是否跳過此行為 yii\behaviors\AttributeBehavior
$value 混合 將指派給目前屬性的值。 yii\behaviors\AttributeBehavior

公開方法

隱藏繼承的方法

方法 描述 定義於
__call() 呼叫未定義為類別方法的具名方法。 yii\base\BaseObject
__construct() 建構子。 yii\base\BaseObject
__get() 傳回物件屬性的值。 yii\base\BaseObject
__isset() 檢查屬性是否已設定,即已定義且非 null。 yii\base\BaseObject
__set() 設定物件屬性的值。 yii\base\BaseObject
__unset() 將物件屬性設為 null。 yii\base\BaseObject
attach() 將行為物件附加到元件。 yii\base\Behavior
canGetProperty() 傳回一個值,指示屬性是否可以讀取。 yii\base\BaseObject
canSetProperty() 傳回一個值,指示屬性是否可以設定。 yii\base\BaseObject
className() 傳回此類別的完整名稱。 yii\base\BaseObject
detach() 從元件中分離行為物件。 yii\base\Behavior
evaluateAttributes() 評估屬性值並將其指派給目前的屬性。 yii\behaviors\AttributeBehavior
events() $owner 的事件宣告事件處理器。 yii\behaviors\AttributeBehavior
hasMethod() 傳回一個值,指示是否已定義方法。 yii\base\BaseObject
hasProperty() 傳回一個值,指示是否已定義屬性。 yii\base\BaseObject
init() 初始化物件。 yii\base\BaseObject

受保護的方法

隱藏繼承的方法

方法 描述 定義於
getValue() 傳回目前屬性的值。 yii\behaviors\AttributeBehavior

屬性詳細資訊

隱藏繼承的屬性

$attributes public property

要自動填入透過 $value 指定之值的屬性列表。陣列鍵是要更新屬性的 ActiveRecord 事件,而陣列值是要更新的對應屬性。您可以使用字串來表示單一屬性,或使用陣列來表示屬性列表。例如:

[
    ActiveRecord::EVENT_BEFORE_INSERT => ['attribute1', 'attribute2'],
    ActiveRecord::EVENT_BEFORE_UPDATE => 'attribute2',
]
public array $attributes = []
$preserveNonEmptyValues public property (自版本 2.0.13 起可用)

是否保留非空的屬性值。

$skipUpdateOnClean public property (自版本 2.0.8 起可用)

$owner 未被修改時,是否跳過此行為

$value public property

將指派給目前屬性的值。這可以是匿名函式、陣列格式的可呼叫 (例如 [$this, 'methodName'])、表示 DB 運算式的 Expression 物件 (例如 new Expression('NOW()'))、純量、字串或任意值。如果是前者,則函式的傳回值將指派給屬性。函式的簽名應如下:

function ($event)
{
    // return value will be assigned to the attribute
}
public mixed $value null

方法詳細資訊

隱藏繼承的方法

__call() public method

定義於: yii\base\BaseObject::__call()

呼叫未定義為類別方法的具名方法。

請勿直接呼叫此方法,因為它是 PHP 魔術方法,當呼叫未知的方法時,將會隱含地呼叫此方法。

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

方法名稱

$params 陣列

方法參數

return 混合

方法傳回值

throws yii\base\UnknownMethodException

當呼叫未知方法時

                public function __call($name, $params)
{
    throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}

            
__construct() public method

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

            
__get() public method

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

傳回物件屬性的值。

請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 $value = $object->property; 時,將會隱含地呼叫此方法。

另請參閱 __set()

public mixed __get ( $name )
$name string

屬性名稱

return 混合

屬性值

throws yii\base\UnknownPropertyException

如果未定義屬性

throws yii\base\InvalidCallException

如果屬性為唯寫

                public function __get($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        return $this->$getter();
    } elseif (method_exists($this, 'set' . $name)) {
        throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
    }
    throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}

            
__isset() public method

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

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

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

請注意,如果未定義屬性,將會傳回 false。

另請參閱 https://php.dev.org.tw/manual/en/function.isset.php

public boolean __isset ( $name )
$name string

屬性名稱或事件名稱

return 布林值

具名屬性是否已設定 (非 null)。

                public function __isset($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        return $this->$getter() !== null;
    }
    return false;
}

            
__set() public method

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

設定物件屬性的值。

請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 $object->property = $value; 時,將會隱含地呼叫此方法。

另請參閱 __get()

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

屬性名稱或事件名稱

$value 混合

屬性值

throws yii\base\UnknownPropertyException

如果未定義屬性

throws yii\base\InvalidCallException

如果屬性為唯讀

                public function __set($name, $value)
{
    $setter = 'set' . $name;
    if (method_exists($this, $setter)) {
        $this->$setter($value);
    } elseif (method_exists($this, 'get' . $name)) {
        throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
    } else {
        throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
    }
}

            
__unset() public method

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

將物件屬性設為 null。

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

請注意,如果未定義屬性,此方法將不會執行任何動作。如果屬性為唯讀,則會擲回例外。

另請參閱 https://php.dev.org.tw/manual/en/function.unset.php

public void __unset ( $name )
$name string

屬性名稱

throws yii\base\InvalidCallException

如果屬性為唯讀。

                public function __unset($name)
{
    $setter = 'set' . $name;
    if (method_exists($this, $setter)) {
        $this->$setter(null);
    } elseif (method_exists($this, 'get' . $name)) {
        throw new InvalidCallException('Unsetting read-only property: ' . get_class($this) . '::' . $name);
    }
}

            
attach() public method

定義於: yii\base\Behavior::attach()

將行為物件附加到元件。

預設實作將設定 $owner 屬性,並附加在 events() 中宣告的事件處理器。如果您覆寫此方法,請務必呼叫父類別實作。

public void attach ( $owner )
$owner yii\base\Component

此行為要附加到的元件。

                public function attach($owner)
{
    $this->owner = $owner;
    foreach ($this->events() as $event => $handler) {
        $this->_attachedEvents[$event] = $handler;
        $owner->on($event, is_string($handler) ? [$this, $handler] : $handler);
    }
}

            
canGetProperty() public method

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

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

如果符合以下條件,則屬性為可讀取:

  • 類別具有與指定名稱相關聯的 getter 方法 (在此情況下,屬性名稱不區分大小寫);
  • 類別具有具有指定名稱的成員變數 (當 $checkVars 為 true 時);

另請參閱 canSetProperty()

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

屬性名稱

$checkVars 布林值

是否將成員變數視為屬性

return 布林值

屬性是否可讀取

                public function canGetProperty($name, $checkVars = true)
{
    return method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name);
}

            
canSetProperty() public method

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

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

如果符合以下條件,則屬性為可寫入:

  • 類別具有與指定名稱相關聯的 setter 方法 (在此情況下,屬性名稱不區分大小寫);
  • 類別具有具有指定名稱的成員變數 (當 $checkVars 為 true 時);

另請參閱 canGetProperty()

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

屬性名稱

$checkVars 布林值

是否將成員變數視為屬性

return 布林值

屬性是否可寫入

                public function canSetProperty($name, $checkVars = true)
{
    return method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name);
}

            
className() public static method
自 2.0.14 版本起已過時。在 PHP >=5.5 上,請改用 ::class

定義於: yii\base\BaseObject::className()

傳回此類別的完整名稱。

public static string className ( )
return string

此類別的完整名稱。

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

            
detach() public method

定義於: yii\base\Behavior::detach()

從元件中分離行為物件。

預設實作將取消設定 $owner 屬性,並分離在 events() 中宣告的事件處理器。如果您覆寫此方法,請務必呼叫父類別實作。

public void detach ( )

                public function detach()
{
    if ($this->owner) {
        foreach ($this->_attachedEvents as $event => $handler) {
            $this->owner->off($event, is_string($handler) ? [$this, $handler] : $handler);
        }
        $this->_attachedEvents = [];
        $this->owner = null;
    }
}

            
evaluateAttributes() public method

評估屬性值並將其指派給目前的屬性。

public void evaluateAttributes ( $event )
$event yii\base\Event

                public function evaluateAttributes($event)
{
    if (
        $this->skipUpdateOnClean
        && $event->name == ActiveRecord::EVENT_BEFORE_UPDATE
        && empty($this->owner->dirtyAttributes)
    ) {
        return;
    }
    if (!empty($this->attributes[$event->name])) {
        $attributes = (array) $this->attributes[$event->name];
        $value = $this->getValue($event);
        foreach ($attributes as $attribute) {
            // ignore attribute names which are not string (e.g. when set by TimestampBehavior::updatedAtAttribute)
            if (is_string($attribute)) {
                if ($this->preserveNonEmptyValues && !empty($this->owner->$attribute)) {
                    continue;
                }
                $this->owner->$attribute = $value;
            }
        }
    }
}

            
events() public method

$owner 的事件宣告事件處理器。

子類別可以覆寫此方法,以宣告應附加到 $owner 元件事件的 PHP 回呼。

當行為附加到擁有者時,回呼將附加到 $owner 的事件;當行為從元件分離時,回呼將從事件中分離。

回呼可以是以下任何一種:

  • 此行為中的方法:'handleClick',等效於 [$this, 'handleClick']
  • 物件方法:[$object, 'handleClick']
  • 靜態方法:['Page', 'handleClick']
  • 匿名函式:function ($event) { ... }

以下是一個範例

[
    Model::EVENT_BEFORE_VALIDATE => 'myBeforeValidate',
    Model::EVENT_AFTER_VALIDATE => 'myAfterValidate',
]
public array events ( )
return 陣列

事件 (陣列鍵) 和對應的事件處理器方法 (陣列值)。

                public function events()
{
    return array_fill_keys(
        array_keys($this->attributes),
        'evaluateAttributes'
    );
}

            
getValue() protected method

傳回目前屬性的值。

此方法由 evaluateAttributes() 呼叫。其傳回值將指派給對應於觸發事件的屬性。

protected mixed getValue ( $event )
$event yii\base\Event

觸發目前屬性更新的事件。

return 混合

屬性值

                protected function getValue($event)
{
    if ($this->value instanceof Closure || (is_array($this->value) && is_callable($this->value))) {
        return call_user_func($this->value, $event);
    }
    return $this->value;
}

            
hasMethod() public method

定義於: yii\base\BaseObject::hasMethod()

傳回一個值,指示是否已定義方法。

預設實作是對 php 函式 method_exists() 的呼叫。當您實作 php 魔術方法 __call() 時,您可以覆寫此方法。

public boolean hasMethod ( $name )
$name string

方法名稱

return 布林值

方法是否已定義

                public function hasMethod($name)
{
    return method_exists($this, $name);
}

            
hasProperty() public method

定義於: yii\base\BaseObject::hasProperty()

傳回一個值,指示是否已定義屬性。

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

  • 類別具有與指定名稱相關聯的 getter 或 setter 方法 (在此情況下,屬性名稱不區分大小寫);
  • 類別具有具有指定名稱的成員變數 (當 $checkVars 為 true 時);

另請參閱

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

屬性名稱

$checkVars 布林值

是否將成員變數視為屬性

return 布林值

屬性是否已定義

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

            
init() public method

定義於: yii\base\BaseObject::init()

初始化物件。

在物件以給定組態初始化之後,會在建構子的結尾呼叫此方法。

public void init ( )

                public function init()
{
}