A hook is a function the product calls when something happens. Hooks are how you react to events without editing product files, which is the only kind of customization an update will not overwrite.
How a hook fires
The product runs a named hook point and passes it an array describing what happened. Every function registered against that name is called, in the order it was registered, with that array. What a hook returns is significant only where the hook point documents a return; most hook points ignore it.
Anything slow — an HTTP call to a third party, a large query — is added directly to the time a customer waits, or to the time the automation takes. Queue slow work rather than doing it in the hook.
Registering a hook
Hooks live in the hooks file of an addon module. The addon and gateway hook caches are rebuilt when extensions change and after an upgrade; a hook added to a file that is never loaded will simply never run, which is the most common reason a new hook appears to do nothing.
- Put the function in your addon’s hooks file, not in a product file.
- Name the function distinctly. Two functions with the same name in different modules is a fatal error, not a warning.
- Register it against the exact hook point name, which is case-sensitive.
- Trigger the event and confirm the hook ran, rather than assuming registration succeeded.
The hook families
Debugging a hook
Hooks debug mode records each hook call and what was passed to it. Turn it on, reproduce the event once, turn it off, then read the log. Leaving it on in production produces a large volume of log data quickly.
An unhandled exception inside a hook on the order pipeline can prevent an order completing. Catch your own errors and log them; do not let them escape into the product’s flow.
Hooks and upgrades
Hook point names are part of the product’s contract and are not renamed casually, but the array passed to a hook can gain keys between releases. Read defensively — check a key exists before using it — rather than assuming a shape.