0

How to make contributed module hook execute only if conditions are met. Those functions seem to get automatically invoked. Environment is a custom module.

examples: 1.

if ($condition) {

   function mymodule_modulename_alter ($parameters) {
     //altering code here
   }

}

2.

    if ($condition) {
           //if condition is met, i call the function included in this custom module
           mymodule_modulename_alter ($parameters)
      }

  function mymodule_modulename_alter ($parameters) {
         //but this function will get auto-invoked! I want it run only if $condition is met.
       }

Thanks

4
  • 1
    Does php allow you to have functions with in an if condition? I suppose it would give a function not found. Jan 26, 2013 at 9:38
  • Mohammed, i reconfigured whole question for better understanding what I need to know. Thanks!
    – NenadP
    Jan 26, 2013 at 9:50
  • 1
    why do you give the condition with in the function itself. rather than out side? so if the condition is met the code would be executed other wise it will just exit the function Jan 26, 2013 at 10:01
  • Because conditions are not known to function inside :) But good one, i could "send" conditions with variable_set () and variable_get (), and check for them! Thanks.
    – NenadP
    Jan 26, 2013 at 10:15

2 Answers 2

3

Let the hook be called, but put your operations(that your hook executes) inside your required condition.

function mymodule_modulename_alter($parameters) {
  if ($condition) {
    // Your code.
  }  
}
2
  • 2
    Also, in my knowledge hooks are not meant to be called from functions. All hooks of a type are called by core when they are supposed to be executed.
    – SGhosh
    Jan 26, 2013 at 10:21
  • Most hooks are cached so if you conditionally DEFINE a function, it will give problems. This is how we usually do. Have a look at hook_form_alter functions there. You will see it in many forms.
    – AKS
    Jan 26, 2013 at 14:30
1

I don't see a need to use variable_get() or variable_set(), rather, IMHO, I'd set this up somewhat like this inside your foo.module file:

<?php

function foo_is_whatever_condition() {

   return true or false based on whatever logic you define

}

function foo_WHATEVER_alter($parameters...) {

   if (foo_is_whatever_condition()) {

      // code for when the condition is true here

   }

}

Now, if I am missing out on why or how "conditions are not known to function inside" please add some more specific details here, because, unless it is some really odd edge case, few things are ever not known or knowable :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.