問題描述
我正在編寫一個外掛,bar,它取決於另一個外掛,foo,被啟用,並且我需要從 foo 的功能在 bar 載入時可用。通常根據目錄名稱按字母順序載入外掛,所以 bar 在 foo 之前載入。如果我將 bar 目錄重新命名為 zbar,那麼它最後被載入並且工作正常,但是我正在尋找一個更加優雅和正確的解決方案。
我遵循了 jsdalton 的改變 active_plugins 選項的方法,並且重新排序陣列以在最後放置條,但是在例項化時,bar 仍然無法訪問 foo 的功能。我已經閱讀了相關的核心程式碼 – 基本上是 wp-settings.php 和 wp-includesload.php 中的 wp_get_active_and_valid_plugins(),而且它似乎是按照 active_plugins 索引的順序載入外掛,所以我無法弄清楚出了什麼問題。
這是在 MultiSite 安裝。酒吧是一個課程,foo 是程式性的。
這是一個 stripped-down 版本的 foo /foo.php
function foo()
{
// stuff
}
這是一個 stripped-down 版本的 bar /bar.php
class bar
{
public function __construct()
{
// ...
$active_plugins = get_option('active_plugins');
print_r($active_plugins);
if( function_exists('foo') )
wp_die("foo exists");
else
wp_die("foo doesn't exist yet");
}
}
}
function this_plugin_last()
{
$wp_path_to_this_file = preg_replace('/(.*)plugins/(.*)$/', WP_PLUGIN_DIR."/$2", __FILE__);
$this_plugin = plugin_basename(trim($wp_path_to_this_file));
$active_plugins = get_option('active_plugins');
$this_plugin_key = array_search($this_plugin, $active_plugins);
if ($this_plugin_key)
{
array_splice($active_plugins, $this_plugin_key, 1);
array_push($active_plugins, $this_plugin);
update_option('active_plugins', $active_plugins);
}
}
add_action("plugins_loaded", "this_plugin_last");
$bar = new bar();
這是 bar 的建構函式的輸出:
Array
(
[0] => foo/foo.php
[1] => bar/bar.php
)
foo doesn't exist yet
最佳解決方案
不要觸控載入順序,改變啟用順序。一個工作例項可以在 this answer 中找到。
次佳解決方案
無論什麼,您的建構函式將始終在程式碼中呼叫操作之前執行。
我曾經遇到過這種情況,你們大多是在那裡做的。
簡單的說 – 把 this_plugin_last 功能裡面的一切註釋掉,並把你的 $ bar = new bar(); 裡面有並且只需在該函式中執行所需的所有邏輯和所需要的內容。這樣可以確保在執行程式碼之前載入 foo(外掛本身並不一定需要在手之前載入,而是依賴於 foo 使用的) 。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。