我正在构建一个插件,我很难处理它的选项。我已经尝试了几种方法,但我想我在这里遇到了一个结构性问题。我很想听听你对这一切的意见,因为我真的不知道如何让它变得更聪明。
我关于选项的主要功能是
获取插件的选项。如果选项表中未定义,请获取默认选项。使用get\\u presets()覆盖这些选项:预设优先于用户定义的选项。有一个钩子可以过滤选项
get\\u default\\u options()-插件的默认选项-获取插件的预设,这些预设为空,但外部插件可以使用过滤器挂钩添加预设。如果定义了预设,它将覆盖匹配选项并灰显后端字段,因此用户无法为其定义自定义值我的问题是:我通常会检查变量($options或$options\\u presets)是否已经定义。如果是,则不会再次填充,也不会触发挂钩。我这样做是为了让代码更快,但我不确定这个想法是否好如果我尝试用过滤器挂钩添加预设,代码通常会变得疯狂(无限循环等等)这是我的代码示例(简化)。我很乐意听取您的意见/想法,使之更好。谢谢
class MyPlugin{
var $options = null;
var $options_presets = null;
function get_options($keys = null){
//populate only once
if ( $this->options === null ) {
$default = self::get_default_options();
//1 - override default options with custom options (user defined)
if ($custom = get_post_meta($this->post_id, \'myPluginOptions\', true)){
$this->options = array_replace_recursive($default, $custom);
}
//2 - override custom options with presets (presets priority is higher)
if ( $presets = $this->get_presets() ){
$this->options = array_replace_recursive($this->options, $presets);
}
//allow plugins to filter the options when they are populated
$this->options = apply_filters(\'my_plugin_get_options\',$this->options,$this);
}
return self::et_array_value($keys,$this->options);
}
function get_default_options($keys = null){
$defaults = array(...); //default options are set here
return self::get_array_value($keys,$defaults);
}
/**
* Get Presets :
* Allow external plugins to define presets; which will override custom options.
* In the plugin options form, a field will be greyed out if a preset is defined.
*/
function get_presets($keys = null){
//populate only once
if ( $this->options_presets === null ) {
$options = get_post_meta($this->post_id, \'myPluginOptions\', true);
//allow plugins to filter the presets when they are populated
$this->options_presets = apply_filters(\'my_plugin_get_presets\',$this->options_presets,$options,$this);
}
return self::get_array_value($keys,$this->options_presets);
}
/**
* Get a value in a multidimensional array
*/
function get_array_value($keys = null, $array){
if (!$keys) return $array;
if (is_string($keys) && isset($array[$keys])) return $array[$keys];
if (!isset($array[$keys[0]])) return false;
if(count($keys) > 1) {
return xspfpl_get_array_value(array_slice($keys, 1), $array[$keys[0]]);
}else{
return $array[$keys[0]];
}
}
}
function add_presets_example($presets,$meta_options,$plugin){
//get options will call get_presets and so the hook my_plugin_get_presets loop and crash the plugin.
//I could eventually unhook - rehook it with :
// remove_filter(\'my_plugin_get_presets\',\'add_presets_example\',10,3);
// add_filter(\'my_plugin_get_presets\',\'add_presets_example\',10,3);
// , but this is extra work and not very clean.
if ($website_url = $plugin->get_options(\'website_url\')) {
...
}
return $presets;
}
add_filter(\'my_plugin_get_presets\',\'add_presets_example\',10,3);