Implementing Basic Python Decorators in PHP
Having just stepped into the world of Python I think it is only human-nature to compare, if not contemplate solutions to, discovered given strengths in a more familiar language. My familiar language being of-course PHP, I thought it would be a good thought experiment to see if I could design a basic decorator implementation in the language. Decorators, as discussed in another post, are an easy concept to explain. Simply put they wrap specified functions with other functions, providing a means to compose new functions in a succinct manner.
PHP provides a means to rename existing user-land functions and subsequently redefine them, by-way of an extension called runkit. For the remainder of the post I will be assuming that you have a sufficient setup configured as a prerequisite. Below is a simple function that uses the ‘runkit’ extension to rename the existing function declaration to a meaningful wrapped name, then includes this new functions name in a call to the wrapper function. This new logic is used to redefine the pre-existing original function name.
Now that we have defined the ‘decorate’ method, lets put it to the test with an arbitrary example. Below highlights an example which specifies a basic ‘hello’ function which we will soon hope to decorate.
We will now define a couple of decorator functions used to log and time the specified functions activity. You will notice looking at the examples below that the functions require a function name and argument array to be supplied which is used to chain the calls together.
With the sample function and decorators now defined we can compose a new function from these individual pieces.
Looking at the example above you can see that we recompose the definition of the original ‘hello’ function to be wrapped by the ‘timer’ and ‘logger’ functions. With this new function we then call it with the argument ‘Bob’ which in-turn invokes the logger and timer functions, before calling the original code.