• 学习yii2.0——行为


    学习yii框架的行为之前,需要先了解yii的事件,可以参考这篇博客:

     怎么理解行为

      yii框架的行为有点类似于trait,可以有个大体的概念:

      1、有一个类A,包含一些属性和方法,很普通的一个类A。

      2、现在需要在这个简单的类中使用类B和类C中的某些属性和方法,或者这两个类中为指定事件绑定的事件处理程序。

      有一种方法可以实现:可以使用组合的方式,在这个简单的类A中,创建其他类(B、C)的对象,然后进行其他的操作,比如访问他们的成员属性和方法。

      yii框架中行为的功能:

      1、在类B和类C声明为行为类,可以在这个行为类中定义属性和方法,以及某些事件对应的事件处理程序。

      2、在类A中的behavior方法中,将前面的两个行为类B、C包含进来,那么就可已使用B、C中的行为和方法了。

      注意这里并没有把B、C实例化,而是直接使用B、C类中的方法和属性。

    <?php
    namespace appcontrollers;
    
    use yiiwebController;
    use yiiaseBehavior;
    
    class Demo {
    	public function Show()
    	{
    		echo "this is demo<br>";
    	}
    }
    
    //自定义的行为类要继承yiiaseBehavior类
    class MyHavior1 extends Behavior
    {
    	public $prop = "hello world 1 <br>";
    
    	//自定义的方法
    	public function test()
    	{
    		echo "this is MyHavior 1 /tetst<br>";
    	}
    
    	public function events()
    	{
    		//指定事件
    		return [
    			"cry" => function() {echo "don't cry 1<br>";},
    			"test" => [new appcontrollersDemo(), "Show"]
    		];
    	}
    }
    
    //自定义的行为类要继承yiiaseBehavior类
    class MyHavior2 extends Behavior
    {
    	public $prop = "hello world 2 <br>";
    
    	//自定义的方法
    	public function test()
    	{
    		echo "this is MyHavior 2 /tetst<br>";
    	}
    
    	public function events()
    	{
    		//指定事件
    		return [
    			"cry" => function() {echo "don't cry 2<br>";},
    			"test" => [new appcontrollersDemo(), "Show"]
    		];
    	}
    }
    
    class HelloController extends Controller 
    {
    	public function behaviors()
    	{
    		return [
    			//返回附加行为,默认是都添加
    			//加载两个行为类,demo和example类似于标签,这里的顺序是有意义的
    			"demo" => MyHavior1::className(),
    			"example" => MyHavior2::className()
    		];
    	}
    
    	public function actionIndex()
    	{
    		//当两个行为behavior有相同的行为的时候,默认以behaviors中先出现优先级高
    		echo $this->prop;  // hello world 1
    		$this->test();  //this is MyHavior/tetst 1
    		$this->trigger("cry"); //don't cry 1  don't cry 2
    
    		//手动从前面behaviors()中选择附加行为
    		$behaviors = $this->getBehavior("example");
    		echo $behaviors->prop;  // hello world 2 
    		$behaviors->test();     // this is MyHavior 2 /tetst
    		$this->trigger("test"); // this is demo   this is demo
    
    		echo "aaa";
    		//手动删除附加的行为,现在只有example有意义了
    		$this->detachBehavior("demo");
    		echo $this->prop;  // hello world 2 
    		$this->test();  //this is MyHavior/tetst 2
    		$this->trigger("cry"); //don't cry 1  don't cry 2
    
    		//从上面的例子中可以看出,事件一旦触发,那么虽然有先后顺序,但是都会执行事件处理程序
    		//但是访问属性和方法时,如果有重复时,默认是第一个为准
    	}
    }
    

      

  • 相关阅读:
    LeetCode数据库178
    LeetCode数据库181
    LeetCode数据库177
    LeetCode数据库176
    HNOI2003 消防局的设立
    HNOI2001 产品加工
    Luogu P1020 关路灯
    NOIP2004 虫食算
    SP2713 GSS4-Can you answer these queries IV
    APIO2008 免费道路
  • 原文地址:https://www.cnblogs.com/-beyond/p/9483365.html
Copyright © 2020-2023  润新知