4-18-2010 Activation
I spent a while working on how I wanted to handle plugin activation for Phorum over this weekend. I investigated using the existing WordPress tables to store the forum information but, in the end, opted to create my own custom ones for one specific reason: it’ll be easier to clean up after myself if someone uninstalls the plugin if my information isn’t strewn throughout the normal blog tables.
That decision made, I had to figure out the best way to handle the CREATE TABLE queries that would be required of the system when the plugin is activated (and updated). I’ve never been a fan of the long column of SQL statements that some plugins use when creating their own tables. I’m big stickler for code that looks pretty and is functional, so I wanted a way to store the CREATE TABLE queries in a secure fashion while also keeping them in a separate file from the main Phorum code.
To that end, I created a folder and in that folder I put the SQL statements. Then, if the tables needed to be changed, I can use file_get_contents() to read in the queries and then use the WordPress dbDelta() function to actually execute them. This worked very well:
1 2 3 4 5 6 7 8 9 10 | $prefix = $wpdb->prefix . self::prefix; $dir = WP_PLUGIN_DIR . "/phorum/sql"; $files = new DirectoryIterator($dir); foreach($files as $file) if(substr($file, -7, 7) == "sql.php") { $table = $prefix . basename($file, ".sql.php"); $query = file_get_contents("$dir/$file"); $query = preg_replace("/<\?php | \?>/", "", $query); $sql .= sprintf($query, $table, DB_CHARSET); } dbDelta($sql); |
There’s an interesting tidbit on line 7 above. I had to add the PHP tags around my statements to avoid them being printed on-screen if someone actually browsed to the files. If they were simply text, then browsers would show the table information to anyone who happened by. This way, the result is a blank screen. It’s not yet the most elegant solution but it works for my purposes of the moment but I’ll probably keep trying to think of a better solution until one presents itself.
