This is just a quick caveat (or reminder). If you delete a variable from the variables table, always clear the cached entry of the variables too. Drupal caches the whole variables table in the cache table in an entry called 'variables'.
Here are two cases (of the many) you'll need this.
When you're writing your own module and you're setting some variables, always clean them up. Fastest way is by issuing a direct query to the database.
/**
* Implementation of hook_uninstall().
*/
function my_module_uninstall() {
db_query("DELETE FROM {variable} WHERE name LIKE 'my_module_%'");
cache_clear_all('variables', 'cache');
}
A second typical case I can come up with is when releasing the cron semaphore after it got 'stuck'.
DELETE FROM variable WHERE name = 'cron_semaphore'; DELETE FROM cache WHERE cid = 'variables';
Comments
Be very careful when deleting your module's variables using "DELETE FROM {variable} WHERE name LIKE 'my_module_%'". You may accidentally delete another module's variables. For example your module is named 'blogger' and there exists another module named 'blogger_integration'. When that SQL is run, any blogger_integration module variables will be erased.
In my module's I've been leaning towards a new approach: I have a function called mymodule_variables():
<?php
function mymodule_variables() {
return array(
'mymodule_var1' => 'var1default',
'mymodule_var2' => 'var2default',
);
}
?>
Then I have a function that I use instead of variable_get:
<?php
function mymodule_var($name) {
static $defaults;
if (!isset($defaults)) {
$defaults = mymodule_variables();
}
$default = isset($defaults[$name]) ? $defaults[$name] : NULL;
return variable_get($name, $default);
}
?>
And now in the uninstall file, I can just loop through the array provided by mymodule_variables to automatically uninstall only mymodule's variables:
<?php
mymodule_uninstall() {
$variables = array_keys(mymodule_variables());
foreach ($variables as $variable) {
variable_del($variable);
}
}
?>
Post new comment