美文网首页
CI 钩子函数的使用

CI 钩子函数的使用

作者: liangxifeng833 | 来源:发表于2019-04-01 11:21 被阅读0次

点击查看官方钩子基本说明

手动调用钩子

  • 修改配置启用钩子
vim application/config/config.php
$config['enable_hooks'] = TRUE;
  • 在 application/config/hooks.php 中配置自定义钩子
//下单成功之后调用, 生成合同号之后
$hook['after_order'][] = array( 
  'class'    => 'SystemHook',
  'function' => 'index',
  'filename' => 'systemHook.php',
  'filepath' => 'hooks/', 
  'params'   => array()
);
  • 钩子类 application/hooks/systemHook.php文件内容:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * 食街钩子文件controller - 钩子文件目的判断登录人是否拥有权限,否则返回主面板。
 * @author: zhanghuan
 * @date: 2014-04-23
 */
class SystemHook 
{
function __construct()
    {

    }

    /**
      * 系统钩子进程,判读是否有权限,无模块权限跳至主面板,无登录权限跳至登陆页
      */
    public function index($params)
    {   
        $a = $this->CI->uri->segment(1);
        $a = $this->CI->uri->segment(2);
        $a = $this->CI->uri->segment(3);
        echo "<script>alert('调用钩子函数成功!;')</script>";
        var_dump($a);
        exit;
    }
}
  • 在需要调用钩子的地方调用, 在controller中调用
  $this->CI->hooks->_call_hook_new('after_order',array('contractNum'=>151211111,'ljyunId'=>512));
  • 在library中调用
  $this->_hooks_call_hook_new('after_order',array('contractNum'=>151211111,'ljyunId'=>512));
  • 注意, 以上在调用的时候, _call_hook_new()方法是我自己定义的, 在CI中并不存在该方法, CI中使用的是 _call_hook() 方法, 并没有第二个参数的接收, 钩子调用函数的文件内容如下: /system/core/Hooks.php, 注意: 文件中含有 liangxifeng 标注的是我自己修改的.
<?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.
 *
 * @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

        if ($CFG->item('enable_hooks') == FALSE)
        {
            return;
        }

        // Grab the "hooks" definition file.
        // If there are no hooks, we're done.

        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;
        }

        $this->hooks =& $hook;
        $this->enabled = TRUE;
    }

    /**
     * Call Hook liangxifeng 自定义钩子调用 自己新增$params参数,目的为了调用方可以传递参数
     * 2019-03-29
     *
     * Calls a particular hook
     *
     * @access  private
     * @param   string  the hook name
     * @return  mixed
     */
    function _call_hook_new($which = '',$params=array())
    {
        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,$params);
            }
        }
        else
        {
            $this->_run_hook($this->hooks[$which],$params);
        }

        return TRUE;
    }

    /**
     * Call Hook
     *
     * Calls a particular hook
     *
     * @access  private
     * @param   string  the hook name
     * @return  mixed
     */
    function _call_hook($which = '')
    {
        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
     * liangxifeng 新增$customParams参数的接收, 目的是接收目标调用者传递过来的动态参数
     * 2019-03-29
     *
     * Runs a particular hook
     *
     * @access  private
     * @param   array   the hook details
     * @return  bool
     */
    function _run_hook($data,$customParams=array())
    {
        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

        if ($this->in_progress == TRUE)
        {
            return;
        }

        // -----------------------------------
        // 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     = '';

        if (isset($data['class']) AND $data['class'] != '')
        {
            $class = $data['class'];
        }

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

        if (isset($data['params']))
        {
            $params = $data['params'];
        }
        //liangxifeng 如果$customParams自定义参数存在,则覆盖hooks配置中的参数
        //2019-03-29
        if(isset($customParams) && is_array($customParams) && !empty($customParams))
        {
            $params = $customParams;
        }
        //2019-03-29

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

        // -----------------------------------
        // Set the in_progress flag
        // -----------------------------------

        $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);
        }

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

}

// END CI_Hooks class

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

相关文章

  • CI 钩子函数的使用

    点击查看官方钩子基本说明 手动调用钩子 修改配置启用钩子 在 application/config/hooks.p...

  • CI(CodeIgniter )钩子的使用

    如果有人用过laravel,那么一定知道中间件,我们用他做授权管理特别爽。我在使用CI时,也在想CI中是否也有类似...

  • 框架:cobra

    使用 钩子函数

  • vue中的钩子函数(二)

    Vue钩子函数 在开发Vue组件时,钩子函数我们会经常用到,但是具体在什么时机,使用哪个钩子函数,会产生什么样的结...

  • react中事件绑定常用方法

    一,绑定到当前实例上 2,在onClick函数使用钩子函数引用方法 3,方法直接用钩子函数 简单总结下

  • Vue 基础 - 自定义指令和 render 函数

    自定义指令 类似组件可以全局注册和局部注册,使用derective注册。 钩子函数 指令定义函数提供了几个钩子函数...

  • vue中的钩子函数

    注意:不要在钩子函数中使用箭头函数,因为钩子函数的上下文指向的就是vue,而箭头函数的this为上一级的作用域上下...

  • vue 完善路由权限

    什么是钩子函数? 主要是给使用者在路由发生变化时进行一些特殊的处理而定义的函数。 为什么要使用路由的钩子函数? 在...

  • react函数式组件与class组件优化性能

    1、class组件,使用showComponentUpdate钩子函数,在函数内部对props和state进行判断...

  • vue-生命周期与钩子函数

    前言:记录下学习vue过程中的生命周期钩子函数,主要分清楚钩子函数的意思,大致什么时候使用。 官方所述:所...

网友评论

      本文标题:CI 钩子函数的使用

      本文链接:https://www.haomeiwen.com/subject/leplbqtx.html