Home Backend Development PHP Tutorial CI框架源码阅览-钩子类hooks.php

CI框架源码阅览-钩子类hooks.php

Jun 13, 2016 pm 12:52 PM
class data function hook hooks

CI框架源码阅读---------钩子类hooks.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * CodeIgniter
 *
 * An open source application development framework for PHP 5.1.6 or newer
 *
 * @package		CodeIgniter
 * @author		ExpressionEngine Dev Team
 * @copyright	Copyright (c) 2008 - 2011, EllisLab, Inc.
 * @license		http://codeigniter.com/user_guide/license.html
 * @link		http://codeigniter.com
 * @since		Version 1.0
 * @filesource
 */

// ------------------------------------

/**
 * CodeIgniter Hooks Class
 *
 * Provides 提供 a mechanism 机制 to extend the base system without hacking.
 * 用户手册地址:http://codeigniter.org.cn/user_guide/general/hooks.html
 * @package		CodeIgniter
 * @subpackage	Libraries
 * @category	Libraries
 * @author		ExpressionEngine Dev Team
 * @link		http://codeigniter.com/user_guide/libraries/encryption.html
 */
class CI_Hooks {

	/**
	 * Determines wether hooks are enabled
	 * 决定钩子是否启用
	 *
	 * @var bool
	 */
	var $enabled		= FALSE;
	/**
	 * List of all hooks set in config/hooks.php
	 *
	 * @var array
	 */
	var $hooks			= array();
	/**
	 * Determines wether hook is in progress, used to prevent 防止 infinte 无限 loops
	 *
	 * @var bool
	 */
	var $in_progress	= FALSE;

	/**
	 * Constructor
	 *
	 */
	function __construct()
	{
		$this->_initialize();
		log_message('debug', "Hooks Class Initialized");
	}

	// --------------------------------

	/**
	 * Initialize the Hooks Preferences 参数,首选项
	 * 初始化钩子
	 * @access	private
	 * @return	void
	 */
	function _initialize()
	{
		$CFG =& load_class('Config', 'core');

		// If hooks are not enabled in the config file
		// there is nothing else to do
		// 如果配置文件中设置了是不允许hooks,则直接返回退出本函数。
		if ($CFG->item('enable_hooks') == FALSE)
		{
			return;
		}

		// Grab the "hooks" definition file.
		// 抓取钩子的定义文件
		// If there are no hooks, we're done.
		// 如果没有定义hooks.php没有定义$hook数组我们直接返回

		if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/hooks.php'))
		{
		    include(APPPATH.'config/'.ENVIRONMENT.'/hooks.php');
		}
		elseif (is_file(APPPATH.'config/hooks.php'))
		{
			include(APPPATH.'config/hooks.php');
		}


		if ( ! isset($hook) OR ! is_array($hook))
		{
			return;
		}
		
		// 将hooks.php 中的$hook数组引用到$this->hooks
		// 开启$this->enabled
		$this->hooks =& $hook;
		$this->enabled = TRUE;
	}

	// --------------------------------

	/**
	 * Call Hook
	 * 外部其实就是调用这个_call_hook函数进行调用钩子程序。
	 * 而此方法中再调用_run_hook去执行相应的钩子。
	 * Calls a particular hook
	 *
	 * @access	private
	 * @param	string	the hook name
	 * @return	mixed
	 */
	function _call_hook($which = '')
	{
		// 判断$this->enabled 是否开启 和 要调用的钩子是否在$htis->hooks中存在。
		if ( ! $this->enabled OR ! isset($this->hooks[$which]))
		{
			return FALSE;
		}
		
		// 判断要调用的钩子是否是一个二维数组,如果是就遍历执行。
		// 如果不是二维数组就直接执行
		// 这里说明,在一个挂钩点可以执行多个钩子,就是通过定义二维数组来实现的。
		if (isset($this->hooks[$which][0]) AND is_array($this->hooks[$which][0]))
		{
			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
	 * 
	 * @access	private
	 * @param	array	the hook details
	 * @return	bool
	 */
	function _run_hook($data)
	{
		/*
		 * $data 就是我们在APPPATH/config/hook.php 定义的hook数组
         * $hook['pre_controller'] = array(
         *        'class'    => 'MyClass',
         *        'function' => 'Myfunction',
         *        'filename' => 'Myclass.php',
         *        'filepath' => 'hooks',
         *        'params'   => array('beer', 'wine', 'snacks')
         *         );
		 *
		 * 由于每一个钩子肯定是由数组组成的
		 * 所以这里就判断$data是不是数组如果不是则返回
		 * 
		 */
		if ( ! 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
		// 如果调用某一个hook,执行某些脚本,而有可能这些脚本里面再会触发其它hook
		// 如果这个其它hook里面又包含了当前
		// 的hook,那么就会进入死循环,这个in_progress的存在就是阻止这种情况。
		
		if ($this->in_progress == TRUE)
		{
			return;
		}

		// -----------------------------------
		// 取出data里面的数据,加载  APPPATH.$data['filepath'].$data['filename'];
        // Set file path
		// -----------------------------------

		if ( ! isset($data['filepath']) OR ! isset($data['filename']))
		{
			return FALSE;
		}

		$filepath = APPPATH.$data['filepath'].'/'.$data['filename'];

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

		// -----------------------------------
		// Set class/function name
		// -----------------------------------

		$class		= FALSE;
		$function	= FALSE;
		$params		= '';
		// 取出$hooks 中的class function params 
		if (isset($data['class']) AND $data['class'] != '')
		{
			$class = $data['class'];
		}

		if (isset($data['function']))
		{
			$function = $data['function'];
		}

		if (isset($data['params']))
		{
			$params = $data['params'];
		}

		if ($class === FALSE AND $function === FALSE)
		{
			return FALSE;
		}

		// -----------------------------------
		// Set the in_progress flag
		// 在开始执行钩子相应的程序之前,先把当前hook的状态设为正在运行中。
		// -----------------------------------
		
		$this->in_progress = TRUE;

		// -----------------------------------
		// Call the requested class and/or function
		// 包含钩子文件并实例化类,调用函数
		// -----------------------------------

		if ($class !== FALSE)
		{
			if ( ! class_exists($class))
			{
				require($filepath);
			}

			$HOOK = new $class;
			$HOOK->$function($params);
		}
		else
		{
			if ( ! function_exists($function))
			{
				require($filepath);
			}

			$function($params);
		}
		// 执行相应程序完毕后,重新把当前hook的状态改为非运行中
		// 以让它可以再次被触发。
		$this->in_progress = FALSE;
		return TRUE;
	}

}

// END CI_Hooks class

/* End of file Hooks.php */
/* Location: ./system/core/Hooks.php */
Copy after login

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use classes and methods in Python How to use classes and methods in Python Apr 21, 2023 pm 02:28 PM

Concepts and instances of classes and methods Class (Class): used to describe a collection of objects with the same properties and methods. It defines the properties and methods common to every object in the collection. Objects are instances of classes. Method: Function defined in the class. Class construction method __init__(): The class has a special method (construction method) named init(), which is automatically called when the class is instantiated. Instance variables: In the declaration of a class, attributes are represented by variables. Such variables are called instance variables. An instance variable is a variable modified with self. Instantiation: Create an instance of a class, a specific object of the class. Inheritance: that is, a derived class (derivedclass) inherits the base class (baseclass)

What does function mean? What does function mean? Aug 04, 2023 am 10:33 AM

Function means function. It is a reusable code block with specific functions. It is one of the basic components of a program. It can accept input parameters, perform specific operations, and return results. Its purpose is to encapsulate a reusable block of code. code to improve code reusability and maintainability.

How to use hooks in vue3 How to use hooks in vue3 May 11, 2023 pm 10:58 PM

1. What is hookshook? Hook means hook. When you see "hook", do you think of hook function? In fact, hooks are really a way of writing functions. vue3 developed CompositionAPI based on reacthooks, so it means that CompositionAPI can also customize encapsulation hooks. Hooks in vue3 are a way of writing functions, which is to extract the js code of some individual functions of the file and put it into a separate js file, or some public methods/functions that can be reused. In fact, hooks are somewhat similar to mixins in vue2, but compared to mixins, hooks are clearer.

Replace the class name of an element using jQuery Replace the class name of an element using jQuery Feb 24, 2024 pm 11:03 PM

jQuery is a classic JavaScript library that is widely used in web development. It simplifies operations such as handling events, manipulating DOM elements, and performing animations on web pages. When using jQuery, you often encounter situations where you need to replace the class name of an element. This article will introduce some practical methods and specific code examples. 1. Use the removeClass() and addClass() methods jQuery provides the removeClass() method for deletion

What does class mean in python? What does class mean in python? May 21, 2019 pm 05:10 PM

Class is a keyword in Python, used to define a class. The method of defining a class: add a space after class and then add the class name; class name rules: capitalize the first letter. If there are multiple words, use camel case naming, such as [class Dog()].

How vue3 hook reconstructs DataV's full-screen container component How vue3 hook reconstructs DataV's full-screen container component May 16, 2023 pm 02:43 PM

Implement the creation component fullScreenContainer.vueimport{useAutoResize}from'@/hooks/useAutoResize' const{autoBindRef}=useAutoResize() to customize a hook and export an autoBindRef binding ref custom hook file useAutoResize.tsimport{ref}from'vue' ;exportfunctionuseAutoResize(){l

How SpringBoot encrypts and protects class files through custom classloader How SpringBoot encrypts and protects class files through custom classloader May 11, 2023 pm 09:07 PM

Background Recently, key business codes have been encrypted for the company framework to prevent the engineering code from being easily restored through decompilation tools such as jd-gui. The configuration and use of the related obfuscation scheme are relatively complex and there are many problems for the springboot project, so the class files are encrypted and then passed The custom classloder is decrypted and loaded. This solution is not absolutely safe. It only increases the difficulty of decompilation. It prevents gentlemen but not villains. The overall encryption protection flow chart is shown in the figure below. Maven plug-in encryption uses custom maven plug-in to compile. The class file specified is encrypted, and the encrypted class file is copied to the specified path. Here, it is saved to resource/corecla.

Detailed explanation of PHP Class usage: Make your code clearer and easier to read Detailed explanation of PHP Class usage: Make your code clearer and easier to read Mar 10, 2024 pm 12:03 PM

When writing PHP code, using classes is a very common practice. By using classes, we can encapsulate related functions and data in a single unit, making the code clearer, easier to read, and easier to maintain. This article will introduce the usage of PHPClass in detail and provide specific code examples to help readers better understand how to apply classes to optimize code in actual projects. 1. Create and use classes In PHP, you can use the keyword class to define a class and define properties and methods in the class.

See all articles