diff --git a/docs/guide/concept-behaviors.md b/docs/guide/concept-behaviors.md index 9f897f7..69e7270 100644 --- a/docs/guide/concept-behaviors.md +++ b/docs/guide/concept-behaviors.md @@ -126,6 +126,16 @@ $component->attachBehavior('myBehavior3', [ ]); ``` +You may attach multiple behaviors at once by using the [[yii\base\Component::attachBehaviors()]] method. +For example, + +```php +$component->attachBehaviors([ + 'myBehavior1' => new MyBehavior, // a named behavior + MyBehavior::className(), // an anonymous behavior +]); +``` + You may also attach behaviors through [configurations](concept-configurations.md). For more details, please refer to the [Configurations](concept-configurations.md#configuration-format) section. diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index edd39e2..c84af37 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -71,6 +71,7 @@ Yii Framework 2 Change Log - Enh #3232: Added `export()` and `exportAsString()` methods to `yii\helpers\BaseVarDumper` (klimov-paul) - Enh #3244: Allow logging complex data such as arrays and object via the log system (cebe) - Enh #3252: Added support for case insensitive matching using ILIKE to PostgreSQL QueryBuilder (cebe) +- Enh #3280: Support dynamically attaching anonymous behaviors (qiangxue) - Enh #3284: Added support for checking multiple ETags by `yii\filters\HttpCache` (qiangxue) - Enh #3298: Supported configuring `View::theme` using a class name (netyum, qiangxue) - Enh #3328: `BaseMailer` generates better text body from html body (armab) diff --git a/framework/base/Component.php b/framework/base/Component.php index 5305538..3480e50 100644 --- a/framework/base/Component.php +++ b/framework/base/Component.php @@ -660,7 +660,9 @@ class Component extends Object /** * Attaches a behavior to this component. - * @param string $name the name of the behavior. + * @param string|integer $name the name of the behavior. If this is an integer, it means the behavior + * is an anonymous one. Otherwise, the behavior is a named one and any existing behavior with the same name + * will be detached first. * @param string|array|Behavior $behavior the behavior to be attached * @return Behavior the attached behavior. */ @@ -669,11 +671,17 @@ class Component extends Object if (!($behavior instanceof Behavior)) { $behavior = Yii::createObject($behavior); } - if (isset($this->_behaviors[$name])) { - $this->_behaviors[$name]->detach(); + if (is_int($name)) { + $behavior->attach($this); + $this->_behaviors[] = $behavior; + } else { + if (isset($this->_behaviors[$name])) { + $this->_behaviors[$name]->detach(); + } + $behavior->attach($this); + $this->_behaviors[$name] = $behavior; } - $behavior->attach($this); - return $this->_behaviors[$name] = $behavior; + return $behavior; } }