在哪里声明模块中不同包含文件共有的变量 - Drupal

Spa*_*rky 4 drupal drupal-6 drupal-modules

我有一个Drupal Module'示例'.我已将模块的管理和客户端功能拆分为两个包含文件example.admin.inc和example.pages.inc.我在example.module文件中声明了常量(define()),可以在pages.inc文件和admin.inc文件中访问它们.

但是如何在集中位置声明普通$变量,以便可以在admin.inc文件和pages.inc文件中访问它们.我试图在example.module中声明$ variable,但无法在example.admin.inc和example.pages.inc中访问它.

Ber*_*dir 7

根据您的需要,有多种可能性.

可覆盖的设置

你可以用variable_get('your_module_your_key', $default_value);.然后,很容易在settings.php中覆盖它$conf['your_module_your_key'] = 'other value';.请参阅http://api.drupal.org/api/drupal/includes--bootstrap.inc/function/variable_get.

为此构建设置表单也很容易,例如参见http://api.drupal.org/api/drupal/modules--menu--menu.admin.inc/function/menu_configure/7.

请注意,您应该始终为变量添加模块名称前缀,并且不要将其用于经常更改的变量,因为每次更改都会导致所有变量都清除缓存.另请注意,所有变量都会在每个页面请求中加载,因此不要创建太多变量或在其中存储大数据结构.它们主要用于配置.

静态获取/设置功能

您可以编写简单的get/set函数,这些函数在内部使用静态来在单个页面请求期间交换变量.例如,参见http://api.drupal.org/api/drupal/includes--path.inc/function/drupal_set_title/6.

请记住,这些内容仅针对单页请求进行保留.这是一个示例实现,它允许保存由字符串标识的多个变量,因此类似于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');
Run Code Online (Sandbox Code Playgroud)

您还可以将其扩展为返回每个引用,依此类推.

高速缓存

要存储来自慢速数据库查询或复杂计算的示例数据,可以使用缓存系统.http://www.lullabot.com/articles/a-beginners-guide-to-caching-data看起来像是一个详细而精彩的解释.

请注意,默认情况下缓存存储在数据库中,但是可插入,例如也可以使用APC或Memcached.