允许 PHP 应用程序插件的最佳方式 [英] Best way to allow plugins for a PHP application

查看:25
本文介绍了允许 PHP 应用程序插件的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 PHP 启动一个新的 Web 应用程序,这一次我想创建一些人们可以使用插件界面扩展的东西.

I am starting a new web application in PHP and this time around I want to create something that people can extend by using a plugin interface.

如何将钩子"写入他们的代码中,以便插件可以附加到特定事件?

How does one go about writing 'hooks' into their code so that plugins can attach to specific events?

推荐答案

您可以使用观察者模式.实现此目的的简单功能方法:

You could use an Observer pattern. A simple functional way to accomplish this:

<?php

/** Plugin system **/

$listeners = array();

/* Create an entry point for plugins */
function hook() {
    global $listeners;

    $num_args = func_num_args();
    $args = func_get_args();

    if($num_args < 2)
        trigger_error("Insufficient arguments", E_USER_ERROR);

    // Hook name should always be first argument
    $hook_name = array_shift($args);

    if(!isset($listeners[$hook_name]))
        return; // No plugins have registered this hook

    foreach($listeners[$hook_name] as $func) {
        $args = $func($args); 
    }
    return $args;
}

/* Attach a function to a hook */
function add_listener($hook, $function_name) {
    global $listeners;
    $listeners[$hook][] = $function_name;
}

/////////////////////////

/** Sample Plugin **/
add_listener('a_b', 'my_plugin_func1');
add_listener('str', 'my_plugin_func2');

function my_plugin_func1($args) {
    return array(4, 5);
}

function my_plugin_func2($args) {
    return str_replace('sample', 'CRAZY', $args[0]);
}

/////////////////////////

/** Sample Application **/

$a = 1;
$b = 2;

list($a, $b) = hook('a_b', $a, $b);

$str  = "This is my sample application\n";
$str .= "$a + $b = ".($a+$b)."\n";
$str .= "$a * $b = ".($a*$b)."\n";

$str = hook('str', $str);
echo $str;
?>

输出:

This is my CRAZY application
4 + 5 = 9
4 * 5 = 20

注意事项:

对于此示例源代码,您必须在要扩展的实际源代码之前声明所有插件.我已经包含了一个示例,说明如何处理传递给插件的单个或多个值.其中最难的部分是编写实际文档,列出传递给每个钩子的参数.

For this example source code, you must declare all your plugins before the actual source code that you want to be extendable. I've included an example of how to handle single or multiple values being passed to the plugin. The hardest part of this is writing the actual documentation which lists what arguments get passed to each hook.

这只是在 PHP 中完成插件系统的一种方法.有更好的选择,我建议您查看 WordPress 文档以获取更多信息.

This is just one method of accomplishing a plugin system in PHP. There are better alternatives, I suggest you check out the WordPress Documentation for more information.

这篇关于允许 PHP 应用程序插件的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆