学习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 app\controllers;

use yii\web\Controller;
use yii\base\Behavior;

class Demo {
	public function Show()
	{
		echo "this is demo<br>";
	}
}

//自定义的行为类要继承yii\base\Behavior类
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 \app\controllers\Demo(), "Show"]
		];
	}
}

//自定义的行为类要继承yii\base\Behavior类
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 \app\controllers\Demo(), "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

		//从上面的例子中可以看出,事件一旦触发,那么虽然有先后顺序,但是都会执行事件处理程序
		//但是访问属性和方法时,如果有重复时,默认是第一个为准
	}
}

  

扫描二维码关注公众号,回复: 2780771 查看本文章

猜你喜欢

转载自www.cnblogs.com/-beyond/p/9483365.html