# My two cents on adding hooks

The other side of using what I deem being developer options is to create them in the code. That’s a lesson I’ve learnt through trial and error; the former being trying to catchup in my general purpose customized plugins with my latest particular needs adding options and the latter being the temptation to foresee my future, and maybe someone else’s, needs and trying to create options for any possible scenario.

## Then add hooks for you and others

Guides about using hooks abound but there are two things I’ve learnt about adding my own hooks in code and using them:

1. Give the hooks clear names
2. Give hooking functions clear names

### Clear hook names

I use the “who, when, what” rule to give hooks a name and am not scared of long hook names; an example might be

route_pages-before-adding_route

And something even more specific like

route_pages-before-adding_route-hello

The “when” part might be optional but the other parts are not.

### Clear functions name

I spend a lot of time debugging hooks and hooked functions in a screen like this one [caption id=“attachment_180” align=“aligncenter” width=“653”] Init hook callbacks[/caption] and using OOP techniques found that calling classes and methods in an ablative way helps reading them later. I’m targetting this information layout specifically to have to go and read code as little as possible and found that the method name is suffiicently ablative when carrying the “conditional, action, target” information for filters and the “conditional, action” information for actions. This way an hook like the one from the section above could have an hooked method like

RouteMetaHandler::maybeUpdateName

I’m not sticking to any more guidelines in my code but the simple one underlying much of what OOP tries to do: “if you can’t name it (a class or a method) then it’s probably doing too much”.

## To protect and to serve

Again out of my experience I’ve come to understand that an hook, be it an action or a filter, should stick to two rules:

1. Protect its context from bad code
2. Serve meaningful information

Just reading WordPress source code is illuminating: filters always undergo a conditional check not to allow any third party hooking function to return non legit objects and values; filters and actions will always serve (passing it as a parameter to called functions) a meningful context.

## Filters and actions on demand

I’ve found that I’m afflicted by a chronic lack of imagination when it comes to imagining myself using a filter or action I’m adding but immediately know what I want when I’d like a filter or action to be there. My current workflow is currently not to add any filter or action until I need one and to always and solely rely on the hooks mechanism to expand functionalities from the first time I need to do so onward.