静态绑定
<?php namespace app\controllers; use Yii; use yii\filters\AccessControl; use yii\web\Controller; use vendor\animal\Cat; use vendor\animal\Mourse; use vendor\animal\Dog; use yii\base\Event; class AnimalController extends Controller { public function actionIndex2() { $dog = new Dog(); $dog->look(); $dog->eat(); $dog->height=100; $dog->trigger('wang'); }
<?php namespace vendor\animal; use app\behaviors\Behavior1; use yii\base\Component; class Dog extends Component{ public function behaviors(){ return [ Behavior1::class, ]; } public function look(){ echo 'i am looking<br/>'; } }
<?php namespace app\behaviors; use yii\base\Behavior; class Behavior1 extends Behavior{ public $height; public function eat(){ echo 'dog eat <br>'; } public function events() { return [ 'wang'=>'shout' ]; } public function shout(){ echo 'wang wang wang <br>'; } }
动态绑定
<?php namespace app\controllers; use Yii; use yii\filters\AccessControl; use yii\web\Controller; use app\behaviors\Behavior1; use vendor\animal\Cat; use vendor\animal\Mourse; use vendor\animal\Dog; use yii\base\Event; class AnimalController extends Controller { /** * Displays homepage. * * @return string */ public function actionIndex() { $cat = new Cat(); $cat2 = new Cat(); $mourse = new Mourse(); $dog = new Dog(); //类级别事件 Event::on(Cat::class,'miao',[$mourse,'run']); //事件的绑定 // $cat->on('miao',[$mourse,'run']); //事件的绑定 顺序 // $cat->on('miao',[$dog,'look'],null,false); $cat->shout(); $cat2->shout(); //全局事件 Yii::$app->on('miao', [$dog,'look']); Yii::$app->trigger('miao'); } public function actionIndex2() { $dog = new Dog(); $behavior1 = new Behavior1(); //将行为绑定到类上 动态绑定 $dog->attachBehavior('beh1',$behavior1); // 访问行为中的属性和方法,就和访问类自身的属性和方法一样 $dog->eat(); $dog->trigger('wang'); } }
<?php namespace vendor\animal; use yii\base\Component; class Dog extends Component{ public function look(){ echo 'i am looking<br/>'; } }
<?php namespace app\behaviors; use yii\base\Behavior; class Behavior1 extends Behavior{ public $height; public function eat(){ echo 'dog eat <br>'; } public function events() { return [ 'wang'=>'shout' ]; } public function shout(){ echo 'wang wang wang <br>'; } }
本文来自博客园,作者:孙龙-程序员,转载请注明原文链接:https://www.cnblogs.com/sunlong88/articles/9670336.html