国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home php教程 php手冊(cè) 深入解讀PHP插件機(jī)制原理

深入解讀PHP插件機(jī)制原理

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

我們?cè)谶@篇文章中主要向大家講了一些

插件,亦即Plug-in,是指一類特定的功能模塊(通常由第三方開發(fā)者實(shí)現(xiàn)),它的特點(diǎn)是:當(dāng)你需要它的時(shí)候激活它,不需要它的時(shí)候禁用/刪除它;且無論是激活還是禁用都不影響系統(tǒng)核心模塊的運(yùn)行,也就是說插件是一種非侵入式的模塊化設(shè)計(jì),實(shí)現(xiàn)了核心程序與插件程序的松散耦合。一個(gè)典型的例子就是Wordpress中眾多的第三方插件,比如Akimet插件用于對(duì)用戶的評(píng)論進(jìn)行Spam過濾。

一個(gè)健壯的PHP插件機(jī)制,我認(rèn)為必須具備以下特點(diǎn):

插件的動(dòng)態(tài)監(jiān)聽和加載(Lookup)

插件的動(dòng)態(tài)觸發(fā)

以上兩點(diǎn)的PHP插件機(jī)制實(shí)現(xiàn)均不影響核心程序的運(yùn)行

要在程序中實(shí)現(xiàn)插件,我們首先應(yīng)該想到的就是定義不同的鉤子(Hooks);“鉤子”是一個(gè)很形象的邏輯概念,你可以認(rèn)為它是系統(tǒng)預(yù)留的插件觸發(fā)條件。它的邏輯原理如下:當(dāng)系統(tǒng)執(zhí)行到某個(gè)鉤子時(shí),會(huì)判斷這個(gè)鉤子的條件是否滿足;如果滿足,會(huì)轉(zhuǎn)而先去調(diào)用鉤子所制定的功能,然后返回繼續(xù)執(zhí)行余下的程序;如果不滿足,跳過即可。這有點(diǎn)像匯編中的“中斷保護(hù)”邏輯。

某些鉤子可能是系統(tǒng)事先就設(shè)計(jì)好的,比如之前我舉的關(guān)于評(píng)論Spam過濾的鉤子,通常它已經(jīng)由核心系統(tǒng)開發(fā)人員設(shè)計(jì)進(jìn)了評(píng)論的處理邏輯中;另外一類鉤子則可能是由用戶自行定制的(由第三方開發(fā)人員制定),通常存在于表現(xiàn)層,比如一個(gè)普通的PHP表單顯示頁面中。

可能你感覺上面的話比較無聊,讓人昏昏欲睡;但是要看懂下面我寫的代碼,理解以上PHP插件機(jī)制的原理是必不可少的。

下面進(jìn)行PHP中插件機(jī)制的核心實(shí)現(xiàn),整個(gè)機(jī)制核心分為三大塊:

一個(gè)插件經(jīng)理類:這是核心之核心。它是一個(gè)應(yīng)用程序全局Global對(duì)象。它主要有三個(gè)職責(zé):

負(fù)責(zé)監(jiān)聽已經(jīng)注冊(cè)了的所有插件,并實(shí)例化這些插件對(duì)象。

負(fù)責(zé)注冊(cè)所有插件。

當(dāng)鉤子條件滿足時(shí),觸發(fā)對(duì)應(yīng)的對(duì)象方法。

插件的功能實(shí)現(xiàn):這大多由第三方開發(fā)人員完成,但需要遵循一定的規(guī)則,這個(gè)規(guī)則是插件機(jī)制所規(guī)定的,因插件機(jī)制的不同而不同,下面的顯示代碼你會(huì)看到這個(gè)規(guī)則。

插件的觸發(fā):也就是鉤子的觸發(fā)條件。具體來說這是一小段代碼,放置在你需要插件實(shí)現(xiàn)的地方,用于觸發(fā)這個(gè)鉤子。

PHP插件機(jī)制原理講了一大堆,下面看看我的實(shí)現(xiàn)方案:

插件經(jīng)理PluginManager類:

以下為PHP插件機(jī)制引用的內(nèi)容:

  1. ?? ?
  2. class?PluginManager ?
  3. { ?
  4. private?$_listeners?=?array(); ?
  5. public?function?__construct() ?
  6. { ?
  7. #這里$plugin數(shù)組包含我們獲取已經(jīng)由用戶
    激活的插件信息 ?
  8. #為演示方便,我們假定$plugin中至少包含 ?
  9. #$plugin?=?array( ?
  10. #?'name'?=>?'插件名稱', ?
  11. #?'directory'=>'插件安裝目錄' ?
  12. #); ?
  13. $plugins?=?get_active_plugins();
    #這個(gè)函數(shù)請(qǐng)自行實(shí)現(xiàn) ?
  14. if($plugins) ?
  15. { ?
  16. foreach($plugins?as?$plugin) ?
  17. {//假定每個(gè)插件文件夾中包含一個(gè)actions.
    php文件,它是插件的具體實(shí)現(xiàn) ?
  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. //獲取插件要實(shí)現(xiàn)的方法 ?
  35. $key?=?get_class($reference).'->'.$method; ?
  36. //將插件的引用連同方法push進(jìn)監(jiān)聽數(shù)組中 ?
  37. $this->_listeners[$hook][$key]?=?
    array(&$reference,?$method); ?
  38. #此處做些日志記錄方面的東西 ?
  39. } ?
  40. function?trigger($hook,?$data='') ?
  41. { ?
  42. $result?=?''; ?
  43. //查看要實(shí)現(xiàn)的鉤子,是否在監(jiān)聽數(shù)組之中 ?
  44. if?(isset($this->_listeners[$hook])?
    &&?is_array($this-
    >_listeners[$hook])?
    &&?count($this-
    >_listeners[$hook])?>?0) ?
  45. { ?
  46. //?循環(huán)調(diào)用開始 ?
  47. foreach?($this->_listeners[$hook]?as?$listener) ?
  48. { ?
  49. //?取出插件對(duì)象的引用和方法 ?
  50. $class?=&?$listener[0]; ?
  51. $method?=?$listener[1]; ?
  52. if(method_exists($class,$method)) ?
  53. { ?
  54. //?動(dòng)態(tài)調(diào)用插件的方法 ?
  55. $result?.=?$class->$method($data); ?
  56. } ?
  57. } ?
  58. } ?
  59. #此處做些日志記錄方面的東西 ?
  60. return?$result; ?
  61. } ?
  62. } ?
  63. ?>?

以上代碼加上注釋不超過100行,就完成了整個(gè)插件機(jī)制的核心。需要再次說明的是,你必須將它設(shè)置成全局類,在所有需要用到插件的地方,優(yōu)先加載。用#注釋的地方是你需要自行完成的部分,包括PHP插件機(jī)制的獲取和日志記錄等等。


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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

Hot Topics

PHP Tutorial
1502
276
PHP calls AI intelligent voice assistant PHP voice interaction system construction PHP calls AI intelligent voice assistant PHP voice interaction system construction Jul 25, 2025 pm 08:45 PM

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

How to use PHP to build social sharing functions PHP sharing interface integration practice How to use PHP to build social sharing functions PHP sharing interface integration practice Jul 25, 2025 pm 08:51 PM

The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization Jul 25, 2025 pm 08:57 PM

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

PHP creates a blog comment system to monetize PHP comment review and anti-brush strategy PHP creates a blog comment system to monetize PHP comment review and anti-brush strategy Jul 25, 2025 pm 08:27 PM

1. Maximizing the commercial value of the comment system requires combining native advertising precise delivery, user paid value-added services (such as uploading pictures, top-up comments), influence incentive mechanism based on comment quality, and compliance anonymous data insight monetization; 2. The audit strategy should adopt a combination of pre-audit dynamic keyword filtering and user reporting mechanisms, supplemented by comment quality rating to achieve content hierarchical exposure; 3. Anti-brushing requires the construction of multi-layer defense: reCAPTCHAv3 sensorless verification, Honeypot honeypot field recognition robot, IP and timestamp frequency limit prevents watering, and content pattern recognition marks suspicious comments, and continuously iterate to deal with attacks.

How to use PHP to combine AI to generate image. PHP automatically generates art works How to use PHP to combine AI to generate image. PHP automatically generates art works Jul 25, 2025 pm 07:21 PM

PHP does not directly perform AI image processing, but integrates through APIs, because it is good at web development rather than computing-intensive tasks. API integration can achieve professional division of labor, reduce costs, and improve efficiency; 2. Integrating key technologies include using Guzzle or cURL to send HTTP requests, JSON data encoding and decoding, API key security authentication, asynchronous queue processing time-consuming tasks, robust error handling and retry mechanism, image storage and display; 3. Common challenges include API cost out of control, uncontrollable generation results, poor user experience, security risks and difficult data management. The response strategies are setting user quotas and caches, providing propt guidance and multi-picture selection, asynchronous notifications and progress prompts, key environment variable storage and content audit, and cloud storage.

PHP realizes commodity inventory management and monetization PHP inventory synchronization and alarm mechanism PHP realizes commodity inventory management and monetization PHP inventory synchronization and alarm mechanism Jul 25, 2025 pm 08:30 PM

PHP ensures inventory deduction atomicity through database transactions and FORUPDATE row locks to prevent high concurrent overselling; 2. Multi-platform inventory consistency depends on centralized management and event-driven synchronization, combining API/Webhook notifications and message queues to ensure reliable data transmission; 3. The alarm mechanism should set low inventory, zero/negative inventory, unsalable sales, replenishment cycles and abnormal fluctuations strategies in different scenarios, and select DingTalk, SMS or Email Responsible Persons according to the urgency, and the alarm information must be complete and clear to achieve business adaptation and rapid response.

Beyond the LAMP Stack: PHP's Role in Modern Enterprise Architecture Beyond the LAMP Stack: PHP's Role in Modern Enterprise Architecture Jul 27, 2025 am 04:31 AM

PHPisstillrelevantinmodernenterpriseenvironments.1.ModernPHP(7.xand8.x)offersperformancegains,stricttyping,JITcompilation,andmodernsyntax,makingitsuitableforlarge-scaleapplications.2.PHPintegrateseffectivelyinhybridarchitectures,servingasanAPIgateway

PHP integrated AI speech recognition and translator PHP meeting record automatic generation solution PHP integrated AI speech recognition and translator PHP meeting record automatic generation solution Jul 25, 2025 pm 07:06 PM

Select the appropriate AI voice recognition service and integrate PHPSDK; 2. Use PHP to call ffmpeg to convert recordings into API-required formats (such as wav); 3. Upload files to cloud storage and call API asynchronous recognition; 4. Analyze JSON results and organize text using NLP technology; 5. Generate Word or Markdown documents to complete the automation of meeting records. The entire process needs to ensure data encryption, access control and compliance to ensure privacy and security.

See all articles