YII自定义第三方扩展

cat.php

<?php
/**
 * Created by PhpStorm.
 * Date: 2016/5/25
 * Time: 15:23
 */
namespace vendor\animal;

use \yii\base\Component;//组件
use \yii\base\Event;//

class myEvent extends Event{
    public $message;
}

class Cat extends Component{
    public function shout(){
        echo "miao miao miao<br>";

        //$this->trigger('miao');//事件命名
        $me = new myEvent();
        $me->message = "hello my Event<br>";

        $this->trigger('miao',$me);
    }
}

Dog.php

<?php
/**
 * Created by PhpStorm.
 * Date: 2016/5/25
 * Time: 17:00
 */
namespace vendor\animal;

use frontend\behaviors\behavior1;
use yii\base\Component;//让一个类拥有接收行为的能力

class Dog extends  Component{
    public function behaviors(){
        return [
            Behavior1::className(),
        ];
    }
    public function look()
    {
       echo "I am looking!<br>";
    }
}

Mouse.php

<?php
/**
 * Created by PhpStorm.
 * Date: 2016/5/25
 * Time: 15:23
 */
namespace vendor\animal;

class Mouse{
    public function run($e)
    {
        echo $e->message;

        echo "I am running!<br>";
    }
}

controllers/AnimalController.php 调用第三方类库

<?php
/**
 * Created by PhpStorm.
 * Date: 2016/5/25
 * Time: 15:27
 */
//YII事件绑定
namespace frontend\controllers;

use yii;
use yii\web\Controller;
use vendor\animal\Cat;
use vendor\animal\Mouse;
use vendor\animal\Dog;
use \yii\base\Event;//类级别的事件绑定必须
use frontend\behaviors\Behavior1;//对象的混合

class AnimalController extends Controller{
    public function actionIndex(){
        $cat = new Cat();
        $mouse = new Mouse();
        $dog = new Dog();

        //对象级别的事件绑定
        $cat->on('miao',[$mouse,'run']);
        $cat->on('miao',[$dog,'look']);
//
//        $cat->off('miao',[$dog,'look']);//取消关注

        //类级别的事件绑定
//        Event::on(Cat::className(),'miao',[$mouse,'run']);//所有的老鼠都会监听这个miao事件
//        Event::on(Cat::className(),'miao',function(){
//            echo "miao event has triggerd!<br>";
//        });

        $cat->shout();



        //\Yii::$app是YII实现的单例模式
//        Yii::$app->on(\yii\base\Application::EVENT_AFTER_REQUEST,function(){
//            echo "event after request";
//        });
    }

    public function actionBehavior()//类的混合
    {
        /*板块1
         * $dog = new Dog();
        $dog->look();
        $dog->eat();*/

        $dog=new Dog();
        $dog->trigger("wang");
    }

    public function actionObject()//对象的混合
    {
        $dog = new Dog();
        $behavior1 = new Behavior1();
        $dog->attachBehavior('beh1',$behavior1);//取个别名,防止冲突
        //$dog->detachBehavior('beh1');//移除对象
        $dog->eat();
    }

}

 

posted @ 2016-05-26 09:50  雨落知音  阅读(496)  评论(0编辑  收藏  举报