問題描述
我最近開始開發插件和主題,我發現我需要使用兩個功能。
有時我想檢查函數/類是否存在,在此之前聲明為這樣:When to check if a function exists
但這被認為是不好的做法。什麼是防止衝突和保持主題的最佳做法?插件獨立工作,沒有安裝一個主題/插件?
最佳解決方案
行動& 過濾器
imho 最好的方法是使用一個動作來將插件功能帶入主題。
示例#1
這是一個小插件來測試這個。
<?php
/** Plugin Name: (#68117) Print Hello! */
function wpse68117_print_hello()
{
echo "Hello World!";
}
add_action( 'wpse68117_say', 'wpse68117_print_hello' );
主題內容:
<?php
/** Template Name: Test »Print Hello!« Plugin */
get_header();
// Now we call the plugins hook
do_action( 'wpse68117_say' );
現在發生什麼/小孩
這樣我們就不用檢查一個函數,一個文件,一個類,一個方法,甚至一個 (不要這樣做) 全局 $variable 的存在。 WP 實習生全球已經為我們這樣做:它檢查鈎子名稱是否是當前過濾器並附加它。如果不存在,沒有任何反應。
示例#2
使用我們的下一個插件,我們附加一個需要一個參數的回調函數。
<?php
/** Plugin Name: (#68117) Print Thing! */
function wpse68117_print_thing_cb( $thing )
{
return "Hello {$thing}!";
}
add_filter( 'wpse68117_say_thing', 'wpse68117_print_thing_cb' );
主題內容:
<?php
/** Template Name: Test »Print Thing!« Plugin */
get_header();
// Now we call the plugins hook
echo apply_filter( 'wpse68117_say_thing', 'World' );
這一次,我們向用户/開發人員提供添加參數的可能性。他可以輸出 echo/print,甚至進一步處理 (如果你有一個數組返回) 。
示例#3
使用第三個插件,我們附加一個需要兩個參數的回調函數。
<?php
/** Plugin Name: (#68117) Print Alot! */
function wpse68117_alot_cb( $thing, $belongs = 'is mine' )
{
return "Hello! The {$thing} {$belongs}";
}
add_filter( 'wpse68117_grab_it', 'wpse68117_alot_cb' );
主題內容:
<?php
/** Template Name: Test »Print Alot!« Plugin */
get_header();
// Now we call the plugins hook
$string_arr = implode(
" "
,apply_filter( 'wpse68117_grab_it', 'World', 'is yours' )
);
foreach ( $string_arr as $part )
{
// Highlight the $thing
if ( strstr( 'World', $part )
{
echo "<mark>{$part} </mark>";
continue;
}
echo "{$part} ";
}
這個插件現在允許我們插入兩個參數。我們可以將其保存到 $variable 中,並進一步處理。
結論
通過使用過濾器和操作,您可以避免不必要的檢查 (比較 function_*/class_*/method_*/file_exists 的速度或使用 in_array()進行搜索以達到 1k(?) 過濾器搜索) 來提供更好的性能。您還可以避免讓所有這些不必要的聲明不設置變量等,因為插件關心這個。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。