本文实例讲述了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 miaobr>"; //$this->trigger('miao');//事件命名 $me = new myEvent(); $me->message = "hello my Eventbr>"; $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(); } }
更多关于Yii相关内容感兴趣的读者可查看本站专题:《Yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。