Home php教程 php手册 深入解读PHP插件机制原理

深入解读PHP插件机制原理

Jun 13, 2016 am 11:11 AM
php principle exist us plug-in article yes mechanism go deep Interpretation

我们在这篇文章中主要向大家讲了一些

插件,亦即Plug-in,是指一类特定的功能模块(通常由第三方开发者实现),它的特点是:当你需要它的时候激活它,不需要它的时候禁用/删除它;且无论是激活还是禁用都不影响系统核心模块的运行,也就是说插件是一种非侵入式的模块化设计,实现了核心程序与插件程序的松散耦合。一个典型的例子就是Wordpress中众多的第三方插件,比如Akimet插件用于对用户的评论进行Spam过滤。

一个健壮的PHP插件机制,我认为必须具备以下特点:

插件的动态监听和加载(Lookup)

插件的动态触发

以上两点的PHP插件机制实现均不影响核心程序的运行

要在程序中实现插件,我们首先应该想到的就是定义不同的钩子(Hooks);“钩子”是一个很形象的逻辑概念,你可以认为它是系统预留的插件触发条件。它的逻辑原理如下:当系统执行到某个钩子时,会判断这个钩子的条件是否满足;如果满足,会转而先去调用钩子所制定的功能,然后返回继续执行余下的程序;如果不满足,跳过即可。这有点像汇编中的“中断保护”逻辑。

某些钩子可能是系统事先就设计好的,比如之前我举的关于评论Spam过滤的钩子,通常它已经由核心系统开发人员设计进了评论的处理逻辑中;另外一类钩子则可能是由用户自行定制的(由第三方开发人员制定),通常存在于表现层,比如一个普通的PHP表单显示页面中。

可能你感觉上面的话比较无聊,让人昏昏欲睡;但是要看懂下面我写的代码,理解以上PHP插件机制的原理是必不可少的。

下面进行PHP中插件机制的核心实现,整个机制核心分为三大块:

一个插件经理类:这是核心之核心。它是一个应用程序全局Global对象。它主要有三个职责:

负责监听已经注册了的所有插件,并实例化这些插件对象。

负责注册所有插件。

当钩子条件满足时,触发对应的对象方法。

插件的功能实现:这大多由第三方开发人员完成,但需要遵循一定的规则,这个规则是插件机制所规定的,因插件机制的不同而不同,下面的显示代码你会看到这个规则。

插件的触发:也就是钩子的触发条件。具体来说这是一小段代码,放置在你需要插件实现的地方,用于触发这个钩子。

PHP插件机制原理讲了一大堆,下面看看我的实现方案:

插件经理PluginManager类:

以下为PHP插件机制引用的内容:

  1.  ?  
  2. class PluginManager  
  3. {  
  4. private $_listeners = array();  
  5. public function __construct()  
  6. {  
  7. #这里$plugin数组包含我们获取已经由用户
    激活的插件信息  
  8. #为演示方便,我们假定$plugin中至少包含  
  9. #$plugin = array(  
  10. # 'name' => '插件名称',  
  11. # 'directory'=>'插件安装目录'  
  12. #);  
  13. $plugins = get_active_plugins();
    #这个函数请自行实现  
  14. if($plugins)  
  15. {  
  16. foreach($plugins as $plugin)  
  17. {//假定每个插件文件夹中包含一个actions.
    php文件,它是插件的具体实现  
  18. if (@file_exists(STPATH .'plugins/'.
    $plugin['directory'].'/actions.php'))  
  19. {  
  20. include_once(STPATH .'plugins/'.
    $plugin['directory'].'/actions.php');  
  21. $class = $plugin['name'].'_actions';  
  22. if (class_exists($class))   
  23. {  
  24. //初始化所有插件  
  25. new $class($this);  
  26. }  
  27. }  
  28. }  
  29. }  
  30. #此处做些日志记录方面的东西  
  31. }  
  32. function register($hook, &$reference,
     $method)  
  33. {  
  34. //获取插件要实现的方法  
  35. $key = get_class($reference).'->'.$method;  
  36. //将插件的引用连同方法push进监听数组中  
  37. $this->_listeners[$hook][$key] = 
    array(&$reference, $method);  
  38. #此处做些日志记录方面的东西  
  39. }  
  40. function trigger($hook, $data='')  
  41. {  
  42. $result = '';  
  43. //查看要实现的钩子,是否在监听数组之中  
  44. if (isset($this->_listeners[$hook]) 
    && is_array($this-
    >_listeners[$hook]) 
    && count($this-
    >_listeners[$hook]) > 0)  
  45. {  
  46. // 循环调用开始  
  47. foreach ($this->_listeners[$hook] as $listener)  
  48. {  
  49. // 取出插件对象的引用和方法  
  50. $class =& $listener[0];  
  51. $method = $listener[1];  
  52. if(method_exists($class,$method))  
  53. {  
  54. // 动态调用插件的方法  
  55. $result .= $class->$method($data);  
  56. }  
  57. }  
  58. }  
  59. #此处做些日志记录方面的东西  
  60. return $result;  
  61. }  
  62. }  
  63. ?> 

以上代码加上注释不超过100行,就完成了整个插件机制的核心。需要再次说明的是,你必须将它设置成全局类,在所有需要用到插件的地方,优先加载。用#注释的地方是你需要自行完成的部分,包括PHP插件机制的获取和日志记录等等。


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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles