Creating Objects on Hooks/Actions

Lets say we had a class that set up some important things. These things needed to be added on the admin_init hook, and they were done in our classes constructor. How would we create our object so they get set up on the admin_init hook?

View the code on Gist.

Some people may try to do one of these:

View the code on Gist.

But none of those will work. add_action requires a second parameter that is callable which means either a function name in a string, or an array with an object and a method name. Clearly to creating an object is not the same as something that can be called, one is something you do, the other is data.

Instead lets change the code, refactor:

View the code on Gist.

Here I’ve created the object immediately without waiting, and moved the logic out of the constructor into a new method. The constructor is for constructing the object, it isn’t intended for doing work, and doing a lot of work in an objects constructor is very bad practice, and in some languages can lead to unintended consequences.

In this constructor I add the hook so that everything is self contained, and register array( $this, 'getStuffDone' ).

We can extend this further to save time with a helper class:

View the code on Gist.

We can now extend this class to add extra items, such as arguments and parameters:

View the code on Gist.

We don’t necessarily have to use the base class, here I use a filter to add messages to the end of post content:

View the code on Gist.

Finally, one has two more ways of doing it. Static methods, and if you’re using PHP 5.3+ you can use closures:

View the code on Gist.

So in conclusion, if you need to do something and you can’t see a way to do it using the language, chances are you need to refactor your code

Leave a Reply

Your email address will not be published. Required fields are marked *