Difference between revisions of "Hooks"

From Dreamwidth Notes
Jump to: navigation, search
(New page: Hooks are usually used to define business logic rules--for example, who to show the navstrip to, or what options to offer the navstrip. == Creating a hook == Basically, you define a hook...)
(No difference)

Revision as of 18:44, 16 March 2009

Hooks are usually used to define business logic rules--for example, who to show the navstrip to, or what options to offer the navstrip.

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.