温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

php实现事件绑定

发布时间:2020-04-06 10:22:27 阅读:1323 作者:china_lx1 栏目:web开发
PHP开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

最近跟踪yii源码  里面涉及到了绑定事件行为之类,于是自己手写了一个最简单的事件绑定实现

class EventHandle {
	
	private static $_map array();

	//类似jquery绑定事件
	public function on($name$callback)
	{
		if(!is_callable($callback))
			return false;
		if(!isset(self::$_map[$name]))
		{
			self::$_map[$name] = array();
		}
		
		self::$_map[$name][] = $callback;
	}
	//触发事件
	public function trigger($name$event)
	{
		if(!isset(self::$_map[$name]))
			return false;

		$function_arr self::$_map[$name];
		foreach($function_arr as $function)
		{
			call_user_func($function$event);
		}
		return true;
	}

	//移除某个事件特定的回调函数
	public function remove($name$callback)
	{
		if(!isset(self::$_map[$name]))
			return false;

		$map self::$_map[$name];
		$pos array_search($callback$maptrue);
		if($pos >= 0)
		{
			array_splice($map$pos1);
			self::$_map[$name] = $map;
		}
		return true;
	}
}

//事件对象
class Event {
	public static $options array();
	public function __construct($options array())
	{
		$this->options = $options;
	}
}

//通过函数当回调函数
function start1($event)
{
	echo 'start1asdaa<br>';
	var_dump($event);
}

//通过类的方法当回调函数
class EventCallback {
	public function start3($event)
	{
		echo 'start3<br>';
	}
}

$eventhandle new EventHandle();

$eventhandle->on('start'"start1");
$eventhandle->on('start'array("EventCallback""start3"));
$eventhandle->remove('start'array("EventCallback""start3"));
$eventhandle->trigger('start'new Event(array('name' => 'hhhh''age' => 25)));

出现的结果如下:

start1asdaa
object(Event)[2]  public 'options' => 
    array (size=2)
      'name' => string 'hhhh' (length=4)
      'age' => int 25

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI

开发者交流群×