【opencart3源码分析】事件类event.php

<?php
/**
 * @package		OpenCart
 * @author		Daniel Kerr
 * @copyright	Copyright (c) 2005 - 2017, OpenCart, Ltd. (https://www.opencart.com/)
 * @license		https://opensource.org/licenses/GPL-3.0
 * @link		https://www.opencart.com
*/

/**
* 事件类
*
* Event System Userguide
* 
* https://github.com/opencart/opencart/wiki/Events-(script-notifications)-2.2.x.x
*/
class Event {
    // 注册事件类实例
	protected $registry;
	protected $data = array();
	
	/**
	 * 构造方法
	 *
	 * @param	object	$route
 	*/
	public function __construct($registry) {
		$this->registry = $registry;
	}
	
	/**
	 * 
	 * 注册事件
	 * @param	string	$trigger
	 * @param	object	$action
	 * @param	int		$priority
 	*/	
	public function register($trigger, Action $action, $priority = 0) {
		$this->data[] = array(
			'trigger'  => $trigger,
			'action'   => $action,
			'priority' => $priority
		);
		
		$sort_order = array();
        // 遍历数据
		foreach ($this->data as $key => $value) {
			$sort_order[$key] = $value['priority'];
		}
        // 返回一个升序的数组
		array_multisort($sort_order, SORT_ASC, $this->data);	
	}
	
	/**
	 * 
	 * 触发事件
	 * @param	string	$event
	 * @param	array	$args
 	*/		
	public function trigger($event, array $args = array()) {
		foreach ($this->data as $value) {
			if (preg_match('/^' . str_replace(array('\*', '\?'), array('.*', '.'), preg_quote($value['trigger'], '/')) . '/', $event)) {
				$result = $value['action']->execute($this->registry, $args);

				if (!is_null($result) && !($result instanceof Exception)) {
					return $result;
				}
			}
		}
	}
	
	/**
	 * 
	 * 取消事件注册
	 * @param	string	$trigger
	 * @param	string	$route
 	*/	
	public function unregister($trigger, $route) {
		foreach ($this->data as $key => $value) {
			if ($trigger == $value['trigger'] && $value['action']->getId() == $route) {
				unset($this->data[$key]);
			}
		}			
	}
	
	/**
	 * 
	 * 清除事件注册
	 * @param	string	$trigger
 	*/		
	public function clear($trigger) {
		foreach ($this->data as $key => $value) {
			if ($trigger == $value['trigger']) {
				unset($this->data[$key]);
			}
		}
	}	
}

猜你喜欢

转载自blog.csdn.net/qq2942713658/article/details/81351660
今日推荐