Behaviors

Behaviors are instances of yii\base\Behavior, or of a child class. Behaviors, also known as mixins, allow you to enhance the functionality of an existing component class without needing to change the class's inheritance. Attaching a behavior to a component "injects" the behavior's methods and properties into the component, making those methods and properties accessible as if they were defined in the component class itself.
Moreover, a behavior can respond to the events triggered by the component, which allows behaviors to also customize the normal code execution of the component.

这两段话,是Yii2官网上对Bahaviors的定义。先尝试着理解第一段话。

下面这个代码非常靠谱的展示了Bahaviors对原有Component功能的扩展:

// 参考了下面链接1,但修改

// Step 1: 定义一个将绑定行为的类
class MyClass extends yii\base\Component
{
  // 空的
}

// Step 2: 定义一个行为类,他将绑定到MyClass上
class MyBehavior extends yii\base\Behavior
{
  // 行为的一个属性
  public $property1 = 'This is a public property in MyBehavior.';
  private $_property2 = 'This is a private property in MyBehavior.';

   public function getProperty2()
    {
        return $this->_property2;
    }

    public function setProperty2($value)
    {
        $this->_property2 = $value;
    }

  // 行为的一个方法
  public function foo()
  {
    return 'Method Foo in MyBehavior is called.';
  }
}

$myClass = new MyClass();
$myBehavior = new MyBehavior();

// Step 3: 将行为绑定到类上
$myClass->attachBehavior('myBehavior', $myBehavior);

// Step 4: 访问行为中的属性和方法,就和访问类自身的属性和方法一样
echo $myClass->property1; 
echo $myClass->getProperty2;
echo $myClass->foo();

此外,注意一下几个class的继承关系:

yii\base\Model      »   yii\base\Component      » yii\base\BaseObject
yii\base\Controller »   yii\base\Component      » yii\base\BaseObject
                        yii\base\Behavior       » yii\base\BaseObject

参考:
1、https://www.ctolib.com/topics-20735.html
2、https://www.jianshu.com/p/63e56d2f51ef

标签: Bahavior, Component

添加新评论