Browse Source

Fixes #3280: Support dynamically attaching anonymous behaviors

tags/2.0.0-rc
Qiang Xue 10 years ago
parent
commit
46041d0c65
  1. 10
      docs/guide/concept-behaviors.md
  2. 1
      framework/CHANGELOG.md
  3. 18
      framework/base/Component.php

10
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.

1
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)

18
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;
}
}

Loading…
Cancel
Save