問題描述
在我的插件中,我使用以下代碼從數據庫中檢索一個選項:
$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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。