Where to declare variables common to different include files in a module - Drupal

匆匆过客 提交于 2019-12-04 11:15:11

There are multiple possibilities, depending on want you want.

Overridable settings

You can use variable_get('your_module_your_key', $default_value);. Then, it is easy to override that either in settings.php with $conf['your_module_your_key'] = 'other value';. See http://api.drupal.org/api/drupal/includes--bootstrap.inc/function/variable_get.

It is also easy to build a settings form for that, see for example http://api.drupal.org/api/drupal/modules--menu--menu.admin.inc/function/menu_configure/7.

Note that you should always prefix your variables with your module name and that you don't use this for variables that change frequently because every change results in a cache clear for all variables. Also note that all variables are loaded on every page request, so don't create too many of them or store big data structures in it. They are mainly meant for configuration.

Static get/set functions

You can write simple get/set functions which use a static internally to exchange variables during a single page request. See for example http://api.drupal.org/api/drupal/includes--path.inc/function/drupal_set_title/6.

Keep in mind that these things are only kept for a single page request. Here is an example implementation which allows to save multiple variables identified by a string and therefor works similar like variable_get()/set().

<?php
function yourmodule_static($key, $value = NULL) {
  static $storage;

  if (isset($value)) {
    $storage[$key] = $value;
  }
  return $storage[$key];
}

// Then, you can use it like this:
your_module_static('key', $value);

// And then in a different function/file:
$value = your_module_static('key');

You could also extend it to return per reference and so on.

Cache

To store for example data from slow database queries or complex calculations, you can use the cache system. http://www.lullabot.com/articles/a-beginners-guide-to-caching-data looks like a detailed and great explanation of that.

Note that the cache is stored in the database by default but is pluggable and can for example also use APC or Memcached.

at the .module file but you need define it as global

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!