开发者

How can I write this Drupal snippet more efficiently?

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 &a开发者_如何学Pythonmp;& 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.


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 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).

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜