简体   繁体   English

如何更有效地编写此Drupal代码段?

[英]How can I write this Drupal snippet more efficiently?

I'm working on a patch to submit to the Registration Code module for Drupal. 我正在修补一个补丁,提交给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. 看起来我应该能够将它减少到一个带有&&结合两个条件的if语句,但我还没有找到允许我这样做的语法或必要的php数组函数。

In case some context helps, the regcode_voucher sub-module allows users to enter their registration code on the user edit page. 在某些上下文有帮助的情况下,regcode_voucher子模块允许用户在用户编辑页面上输入他们的注册码。 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. 上面的代码是补丁的一部分,它允许绕过regcode的hook_user更改。

Code looks like good, what efficient do you want? 代码看起来很好,你想要什么样的效率? Little changes may be: 几乎没有变化:

if (module_exists('regcode_voucher')) {
  $cnfg = variable_get('regcode_voucher_display', null);
  if ($cnfg) {
    // do your actions
  }
}

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. 如果将它们合并以进行优化,那么对于实时处理器,您将赢得“微小”毫秒,但丢失了干净的代码。

Why are you returning an array from variable_get if the variable is not found? 如果找不到变量,为什么要从variable_get返回一个数组? variable_get will always return a string or a serialized array (that needs to be unserialized). variable_get将始终返回一个字符串或一个序列化数组(需要反序列化)。 If I'm missing something, you can use array_key_exists('regcode', variable_get(...)) to check for the array key. 如果我遗漏了某些东西,你可以使用array_key_exists('regcode',variable_get(...))来检查数组键。

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. 这应该工作...注意如果找不到变量,则从variable_get返回“false”作为默认值,这将导致if条件不匹配。 I personally find this more readable than nested if statements (for 3+ conditions I'd nest, though). 我个人认为这比嵌套的if语句更具可读性(尽管我已经嵌套了3个以上的条件)。

if( module_exists('regcode_voucher') && variable_get('regcode_voucher_display', false) ) {
  // stuff
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM