namespace app\components;
use yii\base\Behavior;
class MyBehavior extends Behavior
{
public $prop1;
private $_prop2;
public function getProp2()
{
return $this->_prop2;
}
public function setProp2($value)
{
$this->_prop2 = $value;
}
public function foo()
{
// ...
}
}
namespace app\models;
use yii\db\ActiveRecord;
use app\Components\MyBehavior;
class User extends ActiveRecord
{
public function behaviors()
{
return [
// 匿名的行为,仅直接给出行为的类名称
MyBehavior::className(),
// 名为myBehavior2的行为,也是仅给出行为的类名称
'myBehavior2' => MyBehavior::className(),
// 匿名行为,给出了MyBehavior类的配置数组
[
'class' => MyBehavior::className(),
'prop1' => 'value1',
'prop3' => 'value3',
],
// 名为myBehavior4的行为,也是给出了MyBehavior类的配置数组
'myBehavior4' => [
'class' => MyBehavior::className(),
'prop1' => 'value1',
'prop3' => 'value3',
]
];
}
}
[
'as myBehavior2' => MyBehavior::className(),
'as myBehavior3' => [
'class' => MyBehavior::className(),
'prop1' => 'value1',
'prop3' => 'value3',
],
]
$Component->attachBehaviors([ 'myBehavior1' => new MyBehavior, // 这是一个命名行为 MyBehavior::className(), // 这是一个匿名行为 ]);
$behavior = $Component->getBehavior('myBehavior2');
$behaviors = $Component->getBehaviors();
yii\base\Component::behaviors() yii\base\Component::ensureBehaviors() yii\base\Component::attachBehaviorInternal() yii\base\Behavior::attach()
public function ensureBehaviors()
{
// 为null表示尚未绑定
// 多说一句,为空数组表示没有绑定任何行为
if ($this->_behaviors === null) {
$this->_behaviors = [];
// 遍历 $this->behaviors() 返回的数组,并绑定
foreach ($this->behaviors() as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
}
private function attachBehaviorInternal($name, $behavior)
{
// 不是 Behavior 实例,说是只是类名、配置数组,那么就创建出来吧
if (!($behavior instanceof Behavior)) {
$behavior = Yii::createObject($behavior);
}
// 匿名行为
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;
}
return $behavior;
}
public function attach($owner)
{
$this->owner = $owner;
foreach ($this->events() as $event => $handler) {
$owner->on($event, is_string($handler) ? [$this, $handler] :
$handler);
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有