3

I am writing a custom module for stripe payments and I need to declare constants for CLIENT_ID and CLIENTSECRETKEY.

is it good to declare them in hook_init because then they will available every where ?

module contains other functions like make_payment and add customer etc.

6

hook_init() is not invoked for cached pages, so you could be opening yourself up to a world of pain if you do that.

Constants outside of a class that need to be accessed by several functions are global by nature, so just put them in the global namespace. It's the best way to ensure they're consistently available when you expect them to be.

4
  • you mean i should declare them outside function in .module file ? at top of the file ? – Vikram May 29 '15 at 12:38
  • Yep, exactly. That way they'll implicitly be available inside every function in your module – Clive May 29 '15 at 12:41
  • i always thought that code outside function is not good and against standards. self made myth – Vikram May 29 '15 at 12:44
  • 1
    It depends who's standards you're talking about @Vikram :) As far as Drupal's standards go, putting everything in the global namespace, and providing pseudo-namespacing rather than something provided by the language, is a necessary evil. Certainly for D7, which needs to support versions of PHP earlier than 5.3. Generally speaking, your 'myth' is not a myth at all - polluting the global namespace is widely considered to be bad practice; you just can't get around it when using Drupal, unfortunately. You could ask yourself "should this really be a constant?", though – Clive May 29 '15 at 13:11
3

If you define the variables in hook_init, then it would work for non cached pages. But in case of Cached pages it would not work.

So it is recommended to use hook_boot instead of hook_init.

hook_boot would be provide you variables for cached pages as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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