您好,我正在使用WordPress创建一个插件,因为这个插件的规模相当大,我正在尝试使用OOP来实现我需要的东西
我使用它的方式是在主插件文件中包含所有类,然后plugins_loaded
操作已启动我创建该函数的一个实例以启动__construct
.
我所有的类都在扩展一个helper类,所以我要添加parent::__construct
在我所有的课上__construct
作用
在helper类中,我定义了init
行动。
代码示例:
// main plugin function code
require_once(\'include/helper.php\');
require_once(\'includes/database.php\');
add_action(\'plugins_loaded\', array(\'helper\', \'get_instance\'));
add_action(\'plugins_loaded\', array(\'database\', \'get_instance\'));
// end of main plugin function
// helper class code
class helper {
function __construct() {
add_action(\'init\', \'function_name_1\');
add_action(\'init\', \'function_name_2\');
add_action(\'init\', \'function_name_3\');
add_action(\'init\', \'function_name_4\');
add_action(\'init\', \'function_name_5\');
)
private $instance;
static public function get_instance() {
if (NULL === self::$instance) {
self::$instance = new helper();
}
return $instance;
}
}
// one sample class code
// I probably have like 8 or 10 of these classes
class database extends helper {
function __construct() {
parent::__construct();
add_action(\'init\', \'inner_function_name_1\');
}
private $instance;
static public function get_instance() {
if (NULL === self::$instance) {
self::$instance = new helper();
}
return $instance;
}
}
我的问题是:这种编码方式有效吗?如果没有,请建议最好的方式__construct 函数多次加载,因此init
每次都会有行动,这是一个问题吗?如果是,我该如何避免