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

I have a Drupal Module 'example'. I divided the functionality of the administrator and client modules into two examples include.admin.inc and example.pages.inc. I declared the constants (define ()) in the example.module file, which are available both in the pages.inc file and in the admin.inc file.

But how can I declare normal $ variables in a centralized location so that they can be accessed both in the admin.inc file and in the pages.inc file. I tried to declare the variable $ in example.module, but could not access it in example.admin.inc and example.pages.inc.

+4
source share
3 answers

There are many possibilities, depending on what you want.

Sophisticated Settings

You can use variable_get('your_module_your_key', $default_value); . Then it is easy to override 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 create a settings form for them, for example, http://api.drupal.org/api/drupal/modules--menu--menu.admin.inc/function/menu_configure/7 .

Note that you should always prefix variables with your module name and that you should not use this for variables that change frequently, because every change causes the cache to be cleared for all variables. Also note that all variables are loaded into every page request, so do not create too many of them or store large data structures in it. They are mainly intended for configuration.

Static get / set functions

You can write simple get / set functions that use a static internal 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 stored for only one page request. Here is an implementation example that allows you to store several variables identified by a string, and therefore works like variable_name () / 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 can also expand it to return data, etc.

Cache

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

Please note that the cache is stored in the database by default, but it is connected and can, for example, also use APC or Memcached.

+7
source

in the .module file, but you need to define it as global

+1
source
+1
source

All Articles