我怎样才能更有效地编写这个 Drupal 片段?
我正在开发一个补丁,以提交到 Drupal 的注册代码模块。总之,下面的代码有没有更高效的写法呢?
if (module_exists('regcode_voucher')) {
$cnfg = variable_get('regcode_voucher_display', array('regform' => 'regform'));
if (empty($cnfg['regform'])) {
return;
}
}
看来我应该能够将其简化为一个 if
语句,并使用 &&
组合两个条件,但我还没有找到语法或必要的 php 数组函数可以让我做到这一点。
如果某些上下文有帮助,regcode_voucher 子模块允许用户在用户编辑页面上输入注册码。在我们的网站上,经过“测试”期后,我们希望通过删除注册码字段来简化注册表格;但我们希望用户仍然能够在其帐户编辑页面上输入代码。上面的代码是一个补丁的一部分,该补丁允许绕过 regcode 的 hook_user 更改。
I'm working on a patch to submit to the Registration Code module for Drupal. In short, is there a more efficient way to write the code below?
if (module_exists('regcode_voucher')) {
$cnfg = variable_get('regcode_voucher_display', array('regform' => 'regform'));
if (empty($cnfg['regform'])) {
return;
}
}
It seems like I should be able to reduce it to one if
statement with &&
combining two conditions, but I haven't found the syntax or the necessary php array function that would allow me to do that.
In case some context helps, the regcode_voucher sub-module allows users to enter their registration code on the user edit page. On our sites, after a "beta" period, we want to simplify the registration form by removing the registration code field; but we'd like users to still be able to enter the code on their account edit page. The code above is part of a patch that allows the regcode's hook_user changes to be bypassed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
代码看起来不错,你想要什么效率?小改动可能是:
我不建议合并 if...,代码应该清晰且更容易理解。如果您合并这些进行优化,您将为实时处理器赢得“微小”毫秒,但会丢失干净的代码。
Code looks like good, what efficient do you want? Little changes may be:
And I don't recommend to merge if..., code should be clear and simpler to understand. If you merge these for optimizing, you win "tiny" milliseconds for real-live processors, but lost your clean code.
如果找不到变量,为什么要从variable_get返回一个数组? variable_get 将始终返回字符串或序列化数组(需要反序列化)。如果我遗漏了某些内容,您可以使用 array_key_exists('regcode', variable_get(...)) 来检查数组键。
这应该有效...注意,如果未找到变量,则默认从variable_get返回“false”,这将导致if条件不匹配。我个人认为这比嵌套的 if 语句更具可读性(不过对于 3 个以上的条件,我会嵌套)。
Why are you returning an array from variable_get if the variable is not found? variable_get will always return a string or a serialized array (that needs to be unserialized). If I'm missing something, you can use array_key_exists('regcode', variable_get(...)) to check for the array key.
This should work... note returning "false" from variable_get as a default if the variable is not found, which will cause the if conditions to not match. I personally find this more readable than nested if statements (for 3+ conditions I'd nest, though).