Several weeks ago I started playing with Laravel. Primarily because several colleagues are using it, and have suggested that I take a look at it. During my time reviewing how to build a view template I came across references to
View and other static calls. Initially I was not impressed due to the use of so many static calls. I have come to an understanding about how static calls in certain circumstances can actually enhance code readability.
I’ve learned over the years in my career that static calls are typically an anti-pattern. Particularly they tend to create tight coupling and add difficulty to testing. The over-use of static calls in Laravel initially drove me away, but I gave some of it a second look while trying to figure out how to enhance Foil’s helpers/extensions. In particular it started to make sense in the view templates to see
Html::something() instead of
Initially I was borrowing Laravel’s AliasLoader, and then used Jeremy Lindblom’s XStatic library. Both of these solutions left me wanting a less manual way of setting up the classes from which to make static calls. So I became curious how they were creating the aliases, and I discovered the following:
- Façades (Proxy Pattern really)
What Laravel calls Façades are actually proxies. They don’t encapsulate functionality to make it simpler, but literally proxy static calls into an instantiated object. I’m not sure why façade was chosen as a term, but it seems likely to cause confusion at some point between the two design patterns.
The heart of both Laravel’s AliasLoader and the XStatic library is
class_alias. As it’s name implies we can alias My\Custom\Doodler as Doodler, and have easier access to it through out the rest of the PHP scripts being called.
Due to reasons given earlier I try to stay away from static calls, but I recently used the proxy pattern in an application to handle diagnostic logging. In particular I felt it was a bad choice to inject the class with the logger object JUST to handle logging in one place. So I created a
Log class to handle a static proxy to the instantiated object.
I’ve come to the following conclusions regarding static proxies though:
- They are ok to use in specific circumstances, like my log example above
- View template rendering
I hereby offer an alternative implementation for others to use, released under the MIT license.
Given my spiel on them being bad for testing, why would I use them in my views? It makes code easier, and decouples the views from the renderer. I don’t use Twig or Blade, and prefer straight PHP views, so it also makes my view renderer code smaller, and keeps the views cleaner.
To all the Laravel developers: I advocate the usage of dependency injection over using static proxies when ever possible in your application code, but continue to use them in your views, or when they make sense to use them.
UPDATED: Added links to XStatic and the AliasLoader