接着Benchmark.php往下看,下一个引入的文件是Hooks.php,我们称之为钩子。它的目的是在不改变核心文件的基础上,来修改框架的内部运作流程。具体使用方法参见手册http://codeigniter.org.cn/user_guide/general/hooks.html。

首先看类里面的几个属性,

public $enabled = FALSE;  用来表示钩子是否可用

public $hooks = array();  配置文件中的信息

protected $_objects = array();  缓存用变量,用来储存挂钩点方法对应的对象

protected $_in_progress = FALSE;  表示当前钩子是否正在进程中

  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;
} $this->hooks =& $hook;
$this->enabled = TRUE;
}

再来看看构造函数,$CFG =& load_class('Config', 'core');是加载config组件,用来获取hook的配置(具体的配置获取流程,我们后面分析Config.php时再详细讨论),log_message('info', 'Hooks Class Initialized');用来在日志中记录调用钩子的信息,注意需要在config.php配置中修改log_threshold的对应等级才能记录,具体原理参见前面的Log.php章节。

再往下判断配置中的enable_hooks属性是否设置为了true,如果没有设置那么不继续往下,所以$this->enabled属性不会置为true,实际上意味着此时钩子功能不生效。

接着引入hooks.php文件,并且获取其中配置,若配置信息格式正确,设置$this->enabled = TRUE;

此时构造函数结束,我们接着看call_hook方法。

  public function call_hook($which = '')
{
if ( ! $this->enabled OR ! isset($this->hooks[$which]))
{
return FALSE;
} if (is_array($this->hooks[$which]) && ! isset($this->hooks[$which]['function']))
{
foreach ($this->hooks[$which] as $val)
{
$this->_run_hook($val);
}
}
else
{
$this->_run_hook($this->hooks[$which]);
} return TRUE;
}

钩子功能的之所以生效是因为我们在Codeigniter.php文件中,多次使用了call_hook方法,该方法的参数我们称之为挂钩点,ci中的挂钩点有7个,具体参见文档,不细述。

先判断enabled属性是否为true,并且相应挂钩点的配置内容是否存在,只有上面两个条件都符合才继续往下。

if (is_array($this->hooks[$which]) && ! isset($this->hooks[$which]['function']))这行代码的目的是判断是否多次调用该挂钩点,ci框架支持挂钩点多次调用,只需要在配置中写成数组形式即可。若是,循环对配置执行_run_hook,如不是就不需要循环。

  protected function _run_hook($data)
{
//判断$data是否时合法的可调用结构,如果是的话直接调用
//主要是为了处理ambda 表达式/匿名函数(或闭包)作为钩子的这种情况
if (is_callable($data))
{
is_array($data)
? $data[0]->{$data[1]}()
: $data(); return TRUE;
}
//如果不是数组,说明配置有问题
elseif ( ! is_array($data))
{
return FALSE;
} //规避当前钩子正在执行其他脚本的情况
if ($this->_in_progress === TRUE)
{
return;
} if ( ! isset($data['filepath'], $data['filename']))
{
return FALSE;
} //文件名赋值
$filepath = APPPATH.$data['filepath'].'/'.$data['filename']; if ( ! file_exists($filepath))
{
return FALSE;
} //读取配置内容赋值变量
$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;
} //即将调用挂钩点方法,设置_in_progress为true,阻止再次进入脚本执行
$this->_in_progress = TRUE; //判读$class是否为false,目的是判断配置中是否写了class,若没有写,那么可能
//挂钩点的文件不是class的形式,只有一个函数,直接调用即可
if ($class !== FALSE)
{
//先判断挂钩点对应的对象是否存在
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); //判断类和类中的方法是否存在,若为false,是否钩子的进程变量_in_progress,推出_run_hook方法
if ( ! class_exists($class, FALSE) OR ! method_exists($class, $function))
{
return $this->_in_progress = FALSE;
} //类实例化,并且储存到_objects变量中
$this->_objects[$class] = new $class();
//调用类中的方法
$this->_objects[$class]->$function($params);
}
}
//直接调用文件中的函数
else
{
//检查类是否已经定义,若没有定义那么引入类文件
function_exists($function) OR require_once($filepath); //判断即将调用的方法是否存在,若不存在释放hook进程变量,退出_run_hook方法
if ( ! function_exists($function))
{
return $this->_in_progress = FALSE;
}
//传入参数,调用方法
$function($params);
}
//释放进程变量,返回true,_run_hook方法执行成功
$this->_in_progress = FALSE;
return TRUE;
}

(代码分析写在注释中了)。

Hooks.php文件就是上面的这些内容了,分析完毕,下面贴出全部代码。

class CI_Hooks {

    /**
* Determines whether hooks are enabled
*
* @var bool
*/
public $enabled = FALSE; /**
* List of all hooks set in config/hooks.php
*
* @var array
*/
public $hooks = array(); /**
* Array with class objects to use hooks methods
*
* @var array
*/
protected $_objects = array(); /**
* In progress flag
*
* Determines whether hook is in progress, used to prevent infinte loops
*
* @var bool
*/
protected $_in_progress = FALSE; /**
* Class constructor
*
* @return void
*/
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;
} $this->hooks =& $hook;
$this->enabled = TRUE;
} // -------------------------------------------------------------------- /**
* Call Hook
*
* Calls a particular hook. Called by CodeIgniter.php.
*
* @uses CI_Hooks::_run_hook()
*
* @param string $which Hook name
* @return bool TRUE on success or FALSE on failure
*/
public function call_hook($which = '')
{
if ( ! $this->enabled OR ! isset($this->hooks[$which]))
{
return FALSE;
} if (is_array($this->hooks[$which]) && ! isset($this->hooks[$which]['function']))
{
foreach ($this->hooks[$which] as $val)
{
$this->_run_hook($val);
}
}
else
{
$this->_run_hook($this->hooks[$which]);
} return TRUE;
} // -------------------------------------------------------------------- /**
* Run Hook
*
* Runs a particular hook
*
* @param array $data Hook details
* @return bool TRUE on success or FALSE on failure
*/
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;
} $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;
} $function($params);
} $this->_in_progress = FALSE;
return TRUE;
} }

CI框架源码学习笔记5——Hooks.php的更多相关文章

  1. CI框架源码学习笔记1——index.php

    做php开发一年多了,陆陆续续用过tp/ci/yii框架,一直停留在只会使用的层面上,关于框架内部的结构实际上是不甚了解的.为了深入的学习,决定把CI框架的源码从头到尾的学习一下, 主要因为CI框架工 ...

  2. CI框架源码学习笔记7——Utf8.php

    愉快的清明节假期结束了,继续回到CI框架学习.这一节我们来看看Utf8.php文件,它主要是用来做utf8编码,废话不多说,上代码. class CI_Utf8 { /** * Class const ...

  3. CI框架源码学习笔记2——Common.php

    上一节我们最后说到了CodeIgniter.php,可是这一节的标题是Common.php,有的朋友可能会觉得很奇怪.事实上,CodeIgniter.php其实包含了ci框架启动的整个流程. 里面引入 ...

  4. CI框架源码学习笔记4——Benchmark.php

    我们回到Codeigniter.php上继续往下看,第一个引入的类文件是Benchmark.php,这个文件主要是提供基准测试,具体使用方法参考手册http://codeigniter.org.cn/ ...

  5. CI框架源码学习笔记6——Config.php

    接着上一节往下,我们这一节来看看配置类Config.php,对应手册内容http://codeigniter.org.cn/user_guide/libraries/config.html. clas ...

  6. CI框架源码学习笔记3——Log.php

    上一节说完了Common.php,然而跟代码打交道总是免不了日志记录,所以这一节我们说说Log.php文件. 先看看类里面的几个属性, protected $_log_path;  日志路径 prot ...

  7. CI框架源码阅读笔记4 引导文件CodeIgniter.php

    到了这里,终于进入CI框架的核心了.既然是“引导”文件,那么就是对用户的请求.参数等做相应的导向,让用户请求和数据流按照正确的线路各就各位.例如,用户的请求url: http://you.host.c ...

  8. CI框架源码阅读笔记5 基准测试 BenchMark.php

    上一篇博客(CI框架源码阅读笔记4 引导文件CodeIgniter.php)中,我们已经看到:CI中核心流程的核心功能都是由不同的组件来完成的.这些组件类似于一个一个单独的模块,不同的模块完成不同的功 ...

  9. CI框架源码阅读笔记3 全局函数Common.php

    从本篇开始,将深入CI框架的内部,一步步去探索这个框架的实现.结构和设计. Common.php文件定义了一系列的全局函数(一般来说,全局函数具有最高的加载优先权,因此大多数的框架中BootStrap ...

随机推荐

  1. CSS-MUI:笔记-01

    ylbtech-CSS-MUI:笔记 1. mui-navbar   导航条返回顶部 1.1.样式一 1.2. <div class="mui-navbar-inner mui-bar ...

  2. [Angularjs-学习笔记]工具篇

    因为一开始学习前端知识一直都是在慕课网,所以这次准备学习下angularjs等了好久,终于慕课网出了angularjs的内容,于是准备开始跟着老师的步骤进行学习. 大漠老师关于开发工具的内容讲得比较快 ...

  3. GPT 安装win10

    BIOS EFI ACHI 安装win10 GPT 分区表 支持FAT,FAT32 gpt 理论支持非常多的分区,容量也支持非常大. MBR分区表 支持FAT,FAT32, NTFS 但是分区数量有限 ...

  4. bash姿势-没有管道符执行结果相同于管道符

    听起来比较别口: 直接看代码: shell如下: [root@sevck_linux ~]# </etc/passwd grep root root:x:::root:/root:/bin/ba ...

  5. jackson 进行json与java对象转换 之二

    主要用于测试学习用jackson包实现json.对象.Map之间的转换. 1.准备测试用的Java类 (1)Link类 package test; /** * Description: 联系方式,被u ...

  6. 问题:Oracle出发器;结果:1、Oracle触发器详解,2、Oracle触发器示例

    ORACLE触发器详解 本篇主要内容如下: 8.1 触发器类型 8.1.1 DML触发器 8.1.2 替代触发器 8.1.3 系统触发器 8.2 创建触发器 8.2.1 触发器触发次序 8.2.2 创 ...

  7. java线程游戏之背景图片的移动

    package com.plane; import java.awt.Graphics; import java.awt.Image; import javax.swing.ImageIcon; im ...

  8. filter(函数,可以迭代的对象)

    #!/usr/bin/env python #filter(函数,可以迭代的对象) def f1(x): if x > 22: return True else: return False re ...

  9. oracle DCL-(grant、revoke )

    1.授权GRANT <权限列表> to <user_name>; 2.收回权限REVOKE <权限列表> from <user_name>

  10. 关于android中,菜单按钮点击事件首次执行之后再次执行需要双击按钮的问题

    有时候在获取事件的时候,需要双击才能获取,解决方法很简单,把返回值设为true,那么这个事件就不会再分发了,我预计是设为其他值会继续分发,造成事件的相应混乱