考虑插件A:
$A_message;
add_action(\'plugins_loaded\', function() {
do_action(\'plugin-A:init\');
});
// Hooks allow B to access A (both during initialization of A and elsewhere in WordPress) without having to check if A exists.
add_filter(\'plugin-A:set\', function($msg) {
$A_message = $msg;
}, PHP_INT_MAX);
add_filter(\'plugin-A:get\', function($msg) {
return $A_message;
}, PHP_INT_MIN);
现在,考虑插件B:
add_action(\'plugin-A:init\', function() {
// We\'re 100% sure that A has loaded (if it exists)
// Store what Cheech says in A. (Using a filter allows us to not have to check if A exists).
do_action(\'plugin-A:set\', "Brent! Open the door!");
});
add_filter(\'the_title\', function($title) {
// Get something from A (and we don\'t have to check if it exists).
// If A exists, return what Cheech says; if A does not exist, return what Chong says.
$title = apply_filters(\'plugin-A:get\', "Dave\'s not here, man!");
return $title;
});
大多数代码听起来对您来说都不是什么新鲜事。加载Foo时,它通过以下方式初始化Bar插件
bar_on_plugins_loaded()
和
foo_load_bar()
. 这里的新特点是,Foo不需要做任何花哨的检查来查看Bar是否存在。这是因为
foo_load_bar()
执行由Bar定义的钩子,而不是Bar本身的属性。(很酷吧?)
稍后在代码中请求标题时(如在帖子列表表中)foo_get_bar_message()
和bar_get_message()
将通过以下方式返回在条形图初始化期间设置的条形图值bar_set_message()
. 同样,这一切都是在无需Foo插件检查Bar是否存在的情况下完成的。并且,如果该条不存在,将返回Foo默认值。(特别感谢Cheech and Chong 获得灵感。)
Edit: 在上面的例子中,B更多地依赖于A,而不是相反。但是,你要求A依赖于B,同样的概念在这里也成立。考虑将此添加到插件A中:
// This function is used somewhere in plugin-A ...
function a_func() {
// Not sure if B exists, but we can make B do something if it does.
do_actions(\'plugin-B:some_func\', \'*knock knock knock*\', \'Who Is It?\');
}
这是对插件B的添加:
add_action(\'plugin-B:some_func\', function($cheech, $chong) {
echo \'<p>\'. $cheech .\'<br>\'. $chong .\'</p>\';
}
除了B(如果存在)将所有标题转换为Dave或Brent的消息外,Cheech和Chong的短剧的开头将由插件A在调用其
a_func()
后来在它自己的代码中。根据您的意愿,A不需要做任何事情来检查插件B是否存在。