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

查看:93
本文介绍了允许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.

一个人如何去写'钩子'到他们的code,这样的插件可以附加到特定的事件?

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;

?>

\r
\r

输出:

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

\r
\r

注:

在这个例子中源$ C ​​$ C,你必须声明的实际源$ C ​​$ C之前,你想扩展您的所有插件。我已经包括如何处理被传递给插件单个或多个值的示例。这样做的最难的部分是编写实际的文档,其中列出得到传递给每个钩什么样的参数。

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实现插件系统只有一个方法。有更好的选择,我建议你检查出的字preSS文档了解更多信息。

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.

对不起,看来下划线是由HTML实体通过降价取代?我可以重新发布此code,当这个错误被修正。

编辑:没关系,当你正在编辑只出现这样

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

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