search
HomeBackend DevelopmentPHP ProblemWhat is the principle of php hook

What is the principle of php hook

钩子原理很简单,有些人把事情弄的过于发杂,其实就是调用某个目录下的比如/hook目录下注册在hook函数里面和读取hook配置文件里面的类的方法的一个调用类的方法的功能。

目的就是最少改动代码,改动旧功能,或者增加一些新功能,或者简单说成调用函数都行。

但是读取hook的配置文件,还是需要在系统的里面每次都需要读取,其实就失去了hook的意义,建议只做钩子本身的就好。

相关推荐:《PHP入门教程

参看一下ci的hook,仅截取hook函数核心部分。

<?php
 protected function _run_hook($data) {
        // Closures/lambda functions and array($object, &#39;method&#39;) callables
        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[&#39;filepath&#39;], $data[&#39;filename&#39;])) {
            return FALSE;
        }
        $filepath = APPPATH . $data[&#39;filepath&#39;] . &#39;/&#39; . $data[&#39;filename&#39;];
        if (!file_exists($filepath)) {
            return FALSE;
        }
        $class = empty($data[&#39;class&#39;]) ? FALSE : $data[&#39;class&#39;];
        $function = empty($data[&#39;function&#39;]) ? FALSE : $data[&#39;function&#39;];
        $params = isset($data[&#39;params&#39;]) ? $data[&#39;params&#39;] : &#39;&#39;;
        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);
             // 核心部分 读取参数部分,去实例化类调用方法 传递参数  其实这也是MVC url路由实现的核心,现在很多
//都是使用 call_user_func_array  call_user_func 这两个方法
            }
        } 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;
    }

原理图解

What is the principle of php hook

个人实现版本

如果你觉得麻烦,甚至可以写个方法都行,建议写成一个类,因为有些东西需要更多的信息

What is the principle of php hook

php

include &#39;hook.class.php&#39;;
$rr = new hook();
//$ee = $rr->get_all_class();
$rr->run_hook(&#39;ff&#39;,&#39;ss&#39;,array());
//echo &#39;<pre class="brush:php;toolbar:false">&#39;;
//print_r($ee);
//echo &#39;
';

hook.class.php

class hook {
    public $HOOK_PATH;
    public $PATH; //完整钩子文件目录
    public $object;
    //调用的时候这个类使用的时候,必须在系统的执行流程当中
    public function __construct() {
        $this->HOOK_PATH = &#39;&#39;; //项目的路径,根据你的项目计算路径  
        $current_path = str_replace("\\", "/", getcwd()); //获取当前目录
        //这个地方在实际用的时候看你需要调整
        $this->PATH = $current_path . $this->HOOK_PATH;
    }
    /* 注册钩子 也可以叫做运行钩子
     * $class       类名称
     * $function    方法 
     * $param       方法参数
     */
    public function run_hook($class, $function, $param = array()) {
        include $this->PATH . &#39;/&#39; . $class . &#39;.class.php&#39;;
//        var_dump($this->PATH . &#39;/&#39; . $class . &#39;.class.php&#39;);
//        call_user_func_array(array($class, $function), $param);//只能调用类的静态方法
//        call_user_func(array($class, $function), $param);  //只能调用类的静态方法
//        其他写法
        $this->object = new $class();
        $this->object->$function($param); //这样就可以不用调用静态方法
    }
    //返回当前已经所有的钩子类和方法  不要当前方法调用这个核心类,需要稍微改造,在$hook_array[$key][&#39;function&#39;]的返回
    方法名的时候
    public function get_all_class() {
        //搜寻hook目录下的所有钩子文件,返回数组
//        $this->PATH
//        var_dump($this->PATH);
        $file_array = scandir($this->PATH);
        $hook_array = array();
        foreach ($file_array as $key => $value) {
            if (strpos($value, &#39;.class.php&#39;) == true) {     //扫描路径绝对不能和这个类本身在一个同一个目录下,不然
            会出现重复声明的同名类
                $name = explode(&#39;.&#39;, $value);
                $hook_array[$key][&#39;name&#39;] = $name[&#39;0&#39;] . &#39;钩子类&#39;;
                $hook_array[$key][&#39;url&#39;] = $this->PATH . &#39;/&#39; . $value;
//                include $hook_array[$key][&#39;url&#39;]; 
//                $cc = new $name[&#39;0&#39;]();
//                $hook_array[$key][&#39;function&#39;][] = get_class_methods($cc);
//                $hook_array[$key][&#39;function&#39;][&#39;param&#39;][] = get_class_vars($class_name); //获取方法变量
            }
        }
        return $hook_array;
    }
}

调用的某个类名

ff.class.php 的ss方法

    public function ss() {
//    static public function ss() {
        echo &#39;dddddddddddddddddddd&#39;;
    }

另一个版本

更方便调用

class hooks {
    const Directory_Structure = &#39;/hooks/&#39;; //相对目录的路径  具体项目使用的时候需要调整
    static public function get_path() {
        return str_replace("\\", "/", getcwd());
    }
    static public function run_hook($class, $function, $param = array()) {
       $s =  include self::get_path() . self::Directory_Structure .$class. &#39;.class.php&#39;;
        call_user_func(array($class, $function), $param);  //只能调用类的静态方法
//        其他写法
//        $object = new $class();
//        $object->$function($param); //这样就可以不用调用静态方法
    }
}

使用

include &#39;hooks.class.php&#39;;
hooks::run_hook(&#39;ee&#39;, &#39;vv&#39;,$param =array());
当然也可以这么访问
$foo = new hooks();
$foo->run_hook(&#39;ee&#39;, &#39;vv&#39;,array());
$foo::run_hook(&#39;ee&#39;, &#39;vv&#39;,array());

自 PHP 5.3.0 起,可以用一个变量来动态调用类。但该变量的值不能为关键字 self,parent 或 static。

 钩子是比较灵活的,可以额外增加一个功能代码,使代码更整洁,比如在做什么一些重要操作,创建订单,在创建订单之前需要做些什么,在创建之后做些什么,都可以使用钩子,这样代码更加灵活。

The above is the detailed content of What is the principle of php hook. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

See all articles

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)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.