問題描述

在我的外掛中,我使用以下程式碼從資料庫中檢索一個選項:

$options = get_option('my_plugin_options');

如果我在外掛的各種功能中使用這 10 次,WordPress 會對資料庫進行 10 次查詢,還是僅按 HTTP 請求進行 1 個資料庫呼叫並快取結果?

最佳解決方案

如有疑問,請檢視原始碼。

挖掘到 get_option(),你會看到 (縮寫):

 $value = wp_cache_get( $option, 'options' );

if ( false === $value ) {
    $row = $wpdb->get_row( $wpdb->prepare( "SELECT option_value FROM $wpdb->options WHERE option_name = %s LIMIT 1", $option ) );

    // Has to be get_row instead of get_var because of funkiness with 0, false, null values
    if ( is_object( $row ) ) {
        $value = $row->option_value;
        wp_cache_add( $option, $value, 'options' );
    } else { // option does not exist, so we must cache its non-existence
        $notoptions[$option] = true;
        wp_cache_set( 'notoptions', $notoptions, 'options' );
        return apply_filters( 'default_option_' . $option, $default );
    }
}

首先,WordPress 檢查它是否已經在記憶體中有選項。預設情況下,wp_cache_get()將從 in-memory 資料儲存 (通常只是一個 PHP 變數) 中檢索值。但一些安裝使用更高階的物件快取,將資料儲存在其他位置。

在任一情況下,如果 WordPress 已經知道,wp_cache_get()將返回您的選項值。

如果沒有,那麼 WordPress 將嘗試從資料庫中獲取它。如果資料庫中存在該選項,則 WordPress 會將其快取在記憶體中,然後將其重新提供,從而使後續查詢更快。

如果該選項不存在於資料庫中,那麼 WordPress 會在內部的 「這些選項不存在」 陣列中標記它,因此它不會嘗試稍後查詢並返回一些預設值。

所以,回答你原來的問題:

If I use this 10 times in various functions of my plugin, does WordPress make 10 queries to the database, or does it only make 1 database call per HTTP request and cache the results?

WordPress 將根據 HTTP 請求進行 1 個資料庫呼叫,並快取結果。

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。