CodeIgniter 源码解读之钩子

钩子的使用及原理

CI如同 Laravel、TP 一样提供了 类似 中间件的 功能,支持在控制器执行前及执行后的操作,CI形象的将它比作 钩子 (hooks)。这篇,我们会先写一个使用钩子的例子,然后再去读源码,了解他的使用方式。

  1. 开启钩子(application/config.php)
/*
|--------------------------------------------------------------------------
| Enable/Disable System Hooks
|--------------------------------------------------------------------------
|
| If you would like to use the 'hooks' feature you must enable it by
| setting this variable to TRUE (boolean).  See the user guide for details.
|
*/
$config['enable_hooks'] = TRUE;# FALSE;
  1. 新建钩子(application\hooks\Test_hook.php)
/**
 ** 自定义的钩子函数
 */
class Test_hook {

	public function say()
	{
		return 'i am a method say of Test_hook !';
	}
}
  1. 注册钩子
    首先,我们在官网可以看到钩子有几种触发时机,我们来了解下
pre_system 在系统执行的早期调用,这个时候只有 基准测试类 和 钩子类 被加载了, 还没有执行到路由或其他的流程。
pre_controller 在你的控制器调用之前执行,所有的基础类都已加载,路由和安全检查也已经完成。
post_controller_constructor 在你的控制器实例化之后立即执行,控制器的任何方法都还尚未调用。
post_controller 在你的控制器完全运行结束时执行。
display_override 覆盖 _display() 方法,该方法用于在系统执行结束时向浏览器发送最终的页面结果。 这可以让你有自己的显示页面的方法。注意你可能需要使用 $this->CI =& get_instance() 方法来获取 CI 超级对象,以及使用 $this->CI->output->get_output() 方法来 获取最终的显示数据。
cache_override 使用你自己的方法来替代 输出类 中的 _display_cache() 方法,这让你有自己的缓存显示机制。
post_system 在最终的页面发送到浏览器之后、在系统的最后期被调用。

我们先使用 pre_controller 挂钩点来注册,将程序先 run 起来

$hook['pre_controller'] = array(
    'class'    => 'Test_hook',
    'function' => 'say',
    'filename' => 'Test_hook.php',
    'filepath' => 'hooks',
    'params'   => array()
);

然后,我们在浏览器里访问目标地址,得到
访问后,得到结果
ok,钩子已经成功跑起来了。然后,我们现在去找一下,钩子实现的代码,我们在 CodeIgniter.php 文件 200 Line找到了加载 Hooks 类代码,然后,紧接着,它调用了 Hooks 类的 call_hook 方法,来尝试加载 pre_system 的挂钩点是否存在:

/*
 * ------------------------------------------------------
 *  Instantiate the hooks class
 * ------------------------------------------------------
 */
	$EXT =& load_class('Hooks', 'core');

/*
 * ------------------------------------------------------
 *  Is there a "pre_system" hook?
 * ------------------------------------------------------
 */
	$EXT->call_hook('pre_system');

我们进入到 Hook 类中一看究竟,果断先看构造函数:

public function __construct()
{
	# 加载配置类
	$CFG =& load_class('Config', 'core');
	log_message('info', 'Hooks Class Initialized');

	// If hooks are not enabled in the config file
	// there is nothing else to do
	# 判断是否开启了 钩子
	if ($CFG->item('enable_hooks') === FALSE)
	{
		return;
	}

	// Grab the "hooks" definition file.
	# 判断配置钩子的文件是否存在,存在则引入
	if (file_exists(APPPATH.'config/hooks.php'))
	{
		include(APPPATH.'config/hooks.php');
	}
	# 支持开发环境配置
	if (file_exists(APPPATH.'config/'.ENVIRONMENT.'/hooks.php'))
	{
		include(APPPATH.'config/'.ENVIRONMENT.'/hooks.php');
	}

	// If there are no hooks, we're done.
	if ( ! isset($hook) OR ! is_array($hook))
	{
		return;
	}
	
	# $hook 数组赋值
	$this->hooks =& $hook;
	# 开启钩子标识
	$this->enabled = TRUE;
}

我们可以看到,构造函数在开启钩子的状态下,加载了钩子配置数组,然后,我们在研究下钩子类的 call_hook 函数:

# 方法接受一个参数,就是钩子的名字,也就是支持的那几个,如:pre_system,pre_controller...
public function call_hook($which = '')
{
	# 首先判断是否开启钩子
	if ( ! $this->enabled OR ! isset($this->hooks[$which]))
	{
		return FALSE;
	}
	
	# 钩子配置数组存在且 function 配置项为空
	if (is_array($this->hooks[$which]) && ! isset($this->hooks[$which]['function']))
	{
		# 这里为啥会是遍历钩子呢?
		# 这是因为假如一个钩子 $hooks[pre_controller][] 他可能是多个钩子
		foreach ($this->hooks[$which] as $val)
		{
			# 看啥看,还不赶紧去 _run_hook()
			$this->_run_hook($val);
		}
	}
	else
	{
		$this->_run_hook($this->hooks[$which]);
	}

	return TRUE;
}
protected function _run_hook($data)
{
	// Closures/lambda functions and array($object, 'method') callables
	# 闭包函数调用
	if (is_callable($data))
	{
		is_array($data)
			? $data[0]->{$data[1]}()
			: $data();

		return TRUE;
	}
	elseif ( ! is_array($data))
	{
		return FALSE;
	}

	// -----------------------------------
	// Safety - Prevents run-away loops
	// -----------------------------------

	// If the script being called happens to have the same
	// hook call within it a loop can happen
	# 看注释罗,不解释罗
	if ($this->_in_progress === TRUE)
	{
		return;
	}

	// -----------------------------------
	// Set file path
	// -----------------------------------
	# 判断 路径 和 文件名 是否存在
	if ( ! isset($data['filepath'], $data['filename']))
	{
		return FALSE;
	}
	# 拼接钩子实现类(Test_hook)文件路径
	$filepath = APPPATH.$data['filepath'].'/'.$data['filename'];

	if ( ! file_exists($filepath))
	{
		return FALSE;
	}

	// Determine and class and/or function names
	# 获取 类名、方法名、传参
	$class		= empty($data['class']) ? FALSE : $data['class'];
	$function	= empty($data['function']) ? FALSE : $data['function'];
	$params		= isset($data['params']) ? $data['params'] : '';

	if (empty($function))
	{
		return FALSE;
	}

	// Set the _in_progress flag
	$this->_in_progress = TRUE;

	// Call the requested class and/or function
	if ($class !== FALSE)
	{
		// The object is stored?
		if (isset($this->_objects[$class]))
		{
			if (method_exists($this->_objects[$class], $function))
			{
				# 执行方法
				$this->_objects[$class]->$function($params);
			}
			else
			{
				return $this->_in_progress = FALSE;
			}
		}
		else
		{
			class_exists($class, FALSE) OR require_once($filepath);

			if ( ! class_exists($class, FALSE) OR ! method_exists($class, $function))
			{
				return $this->_in_progress = FALSE;
			}

			// Store the object and execute the method
			# 保存已实例化的钩子类,避免重复实例化
			$this->_objects[$class] = new $class();
			# 执行钩子函数
			$this->_objects[$class]->$function($params);
		}
	}
	else
	{
		function_exists($function) OR require_once($filepath);

		if ( ! function_exists($function))
		{
			return $this->_in_progress = FALSE;
		}
		# 类名为空时,直接调用方法,该方法可能是 Common.php 文件定义的,
		# 或者必须在加载钩子之前加载
		$function($params);
	}

	$this->_in_progress = FALSE;
	return TRUE;
}

整个钩子的实现过程,大家都熟悉了吧,其实是非常简单的,我们认真的童鞋,应该能发现 CodeIgniter.php 中也不缺乏还有这样的语句:

/*
 * ------------------------------------------------------
 *  Is there a "pre_controller" hook?
 * ------------------------------------------------------
 */
	$EXT->call_hook('pre_controller');

/*
 * ------------------------------------------------------
 *  Is there a "post_controller" hook?
 * ------------------------------------------------------
 */
	$EXT->call_hook('post_controller');
/*
 * ------------------------------------------------------
 *  Send the final rendered output to the browser
 * ------------------------------------------------------
 */
	if ($EXT->call_hook('display_override') === FALSE)
	{
		$OUT->_display();
	}

/*
 * ------------------------------------------------------
 *  Is there a "post_system" hook?
 * ------------------------------------------------------
 */
	$EXT->call_hook('post_system');

ok,感兴趣的童鞋,可以修改钩子的类型,去研究下吧~~这期就说到这,咱们下期再见!!

发布了8 篇原创文章 · 获赞 0 · 访问量 124

猜你喜欢

转载自blog.csdn.net/weixin_43950095/article/details/104646260