gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 23:08:14 24 4
gpt4 key购买 nike

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

但是我怎样才能在一个集中的位置声明普通的 $variables,以便它们可以在 admin.inc 文件和 pages.inc 文件中访问。我试图在 example.module 中声明 $variable,但无法在 example.admin.inc 和 example.pages.inc 中访问它。

最佳答案

有多种可能性,取决于你想要的。

可覆盖的设置

您可以使用 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');

您还可以将其扩展为按引用返回,依此类推。

缓存

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

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

关于drupal - 在哪里声明模块中不同包含文件共有的变量 - Drupal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6041471/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com