By optalgin on
In some modules I see implementation of hook_load like
function hook_load() {
static $loaded = FALSE;
if (!$loaded) {
...
}
?>
Can someone please explain the situation when hook_load is called more then once?
(-or- why do we need $loaded)
Thanks
Comments
I am asking about this code
A pointer to actually code
A pointer to actually code would help as your snippet does not make much sense. hook_load() takes $node as an argument and is used by modules that create their own content type to add their custom fields. Since one can generally display a list of content that might include more than one instance of a content type, a simple
if ( !$loaded ) {does not make much sense so it is hard to answer your question from the small snippet.hook_init and hook_load
I was confused between hook_init and hook_load
hook_init - is module initialization which is called once for each request
hook_load - is call for each node and is used to get additional information for that node
but still in many modules I can see something like this:
Giant HINT, point to a real
Giant HINT, point to a real case (ie module that does this), the snippet in the abstract does not make much sense.
You can see it in...
You can see that exact pattern in the following modules (and more):
I just now notice they are all from the same contributor nedjo..
What looks like a hook but
What looks like a hook but is not a hook? :) In this case collapsiblock_load() is not a hook and I would say it is generally bad practice to use a hook name that is not a hook. Generally it will lead to problems but in the case of hook_load() it is only invoked for a module if it provides a content type.
Why there are not just using hook_init() directly would be a question for the contributor. The pairing of hook_init() and
if ( $loaded ) {is used to make sure something gets done once and only once for each page.Thanks
Thanks @nevets
I understand the use of static $loaded but isn't that unnecessary with hook_init()
(The real hook, not in something that looks like it :-)
Is it possible that hook_init is called twice (and I don't mean calling it explicitly within my module)
Thanks again
A guess, the code may have
A guess, the code may have ported from Drupal 5 where it was not uncommon to do something similar but in that case often call the function from hook_menu(). But that is just a guess.
Explanation
I tend to put the once-only loading code for a module in a separate function so that it can be invoked as needed from e.g.
hook_form_alter()or from another module.Indeed, it would be better not to name these functions like
hook_load()functions, which they are not.Thanks nedjo
I love your modules :-)
Learned a lot from your code, thanks!