Decorating Action classes using generated proxies

Rémi Collin
2 min readMay 29, 2018

--

This post is just a quick addendum to the post Keeping your Laravel applications DRY with single action classes. Some readers asked some details on how to generate decorators for multiple action classes at once.

For this trick, I used the ProxyManager library. This package provides several different strategies which allow us to execute code before and/or after executing an object’s method or accessing one of its property. I won’t get into the details as it’s a complex project, but I encourage you to read the docs if you’re curious, as it provides some functionalities that are not available in native PHP.

Now, let’s dive into our subject.

Logging user actions using the decorator pattern

In the previous post, I used this example on how we could use a class to decorate one of our actions and have Laravel’s container inject it if the application’s configuration has the logging enabled.

This works very well for a single class. But what if we want to decorate multiple classes with the same code ? In a project I worked on at Code16, I needed to log every user actions, and there was around a 100 single actions classes. If I took the previous approach, I should have repeat the same code 100 times.

ProxyManager to the rescue

So, In order again not to duplicate code, I wrote a class which binds in the container every action that I pass to it as a parameter, to a closure that will automatically generate a proxy that extends the requested class, and adds a function that write to laravel’s Log. (wow that was a long phrase)

Here’s the simplified version :

Of course, it’s just a simplified version. In the actual implementation I do more stuff, like parsing the parameters & return value to identify the Entities used in the action, and write to a database table with a polymorphic relationship to the user.

That’s it. I just wanted to share this little trick with you and showcase a bit this awesome library which opened lots of exciting possibilities to me, and I hope to you as well.

--

--