Hooks

From Dreamwidth Notes
Revision as of 20:24, 16 March 2009 by Foxfirefey (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Hooks are usually used to define business logic rules--for example, who to show the navstrip to, or what options to offer the navstrip. Because of this, they are intended to be implemented by the people running the service, and they don't come automatically. For a list of all hooks used in the code, look at the hook list.

Creating a hook

Basically, you define a hook and later in the main code check whether the hook exists and/or run it. Hooks are defined in $LJHOME/cgi-bin/DW/Hooks and named HookName.pm.

An example hook would be:

package DW::Hooks::$HookName; # same as filename
 
LJ::register_hook( 'hook_name', sub {
    # some logic.
    # return something
});
 
1;

(Note that you're going to want to have the recommended file header.)

Having HookName as a package is just for convenience--it makes it easier to match hooks to their functions and modules to hooks, so it's good practice to separate them and keep related hooks in separate files, even though you can register multiple hooks in a single file.

Checking if a hook exists

Sometimes you'll want to check whether a hook exists (for example, to determine whether you should show a link to a page). To do that, use something like:

if LJ::are_hooks('hook_name') { 
    # logic here
}

Using the hook

To run the hook, use something like:

LJ::run_hooks( 'hook_name', args... )

These args can be passed as a hashref or directly, depending on the hook.