I'm developing wordpress plugin which store data in database. I tried to start OOP way for my plugin according to boilerplate from Best Practicies: https://github.com/DevinVinson/WordPress-Plugin-Boilerplate/tree/master/plugin-name
Thing I can't understand is how to call creating tables method only one time - on plugin installation event and make all interactions secure. Also, I want to schedule some load tasks via cron.
I figured out that there are two ways for first goal:
Make all methods public static so db loader class become just wrapper around wpdb instance. But it's not enough secure, isn't it?
Initialize db loader instance every time when plugin needs. (with private methods and so on)
The question is how to initialize db loader class instance correctly to create all tables only one time and avoid public static methods?
This is code from boilerplate:
/**
* Core plugin class
*/
require_once plugin_dir_path(__FILE__) . 'includes/class_my_plugin.php';
function run_my_plugin() {
$plugin = new my_plugin();
$plugin->run();
}
run_my_plugin();
It's main plugin class example:
class my_plugin {
private
$wpdb,
$table_prefix,
$charset_collate;
public function __construct() {
global $wpdb;
$this->wpdb = &$wpdb;
$this->table_prefix = $this->wpdb->prefix . 'test_private_';
$charset_collate = $this->wpdb->get_charset_collate();
}
public function run() {
$table_name = $this->table_prefix . 'desks';
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
some_id int(11) NOT NULL AUTO_INCREMENT,
some_title VARCHAR(50) NOT NULL,
PRIMARY KEY (desk_id)
) $this->charset_collate;";
dbDelta($sql);
}
}