When using variable_get()
in multiple places, how should one avoid duplicating the $default
values?
define()
? Or is there some built-in Drupal-specific mechanism I'm missing?
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this communityThere is no built in mechanism. In fact, there is a long standing issue to add one http://drupal.org/node/145164.
Defining constants, as you suggested, is the only method I've seen to make it a bit cleaner.
A pattern that I often use in custom code, uses OOP. I use this for variable_get, t() and "magic" numbers such as the amount of items in a pager- or limit-query:
class MyModuleHelper() {
public static $foo = "bar";
public function v($name) {
return variable_get("mymodule.{$name}", $$name);
}
public function t($identifier, $params) {
$translated = "";
$callback = "t_{$identifier}";
if (function_exist($callback, $this)) {
$untranslated = $callback();
return t("mymodule." . $untranslated, $params);
}
return $translated;
}
private function t_thank_you() {
return "Thank you, %username";
}
}
Then, in the module:
$helper = new MyModuleNameHelper();
print "Variable foo:" . $helper->v("foo")
print "Translate thank_you:" . $helper->t("thank_you")
This has several advantages:
mymodule.
, whithout duplicating that prefix all over the place (DRY!). t("thank_you")
instead of t("Thank you, %username")
. And one downside: