問題描述

我最近開始開發外掛和主題,我發現我需要使用兩個功能。

有時我想檢查函式/類是否存在,在此之前宣告為這樣: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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。