Functional vs. Object-Oriented PHP
I was asked a seemingly-innocuous question lately that actually turned out to be pretty interesting: “Do you do much object-oriented programming in PHP, like design patterns?” (I’m paraphrasing, actually, I am terrible at remembering exact quotes.) And while I very frequently find myself pretty deep in class structures, I wouldn’t say I do a lot of design-pattern-style OO programming.
Honestly, I find that – at least for PHP – a great many design patterns are completely unnecessary. PHP has enough functional chops that you can avoid needing to implement many of the uglier patterns, although you’re going to find people who try, I’m sure.
Some Good Patterns, Though
The Observer pattern is pretty solid, honestly. Essentially, you can use it to allow objects to “observe” specific points in time and specific events, and then react to them. The really nice thing about intelligently implementing the Observer, is that it makes it very easy to extend a base engine with modular add-ons. You can then turn on or off these modules without affecting the rest of your application, and debugging becomes a lot easier too.
When Are Patterns Better?
There are definitely some situations where I prefer design patterns to functional programming, specifically in the case of factories vs. currying. Since I’m far more likely to be working with many sets of objects instead of bunches of discrete functions, factories are easier to understand and use, even though you can use currying to build your own frankenfunctions to do similar things.
When are Functional Methods Better?
Oh man, I love passing functions as parameters in PHP. How about for when you want to do a custom array sort? Or when you want to trim every string in an array? Or setting up that Observer pattern above, triggering events inside your main engine? It’s such good times.
Compare this to the Chain of Command Pattern. Just look at that crazy thing. Holy moly.
I’ll just pass functions, thanks.
So Why Shoehorn Design Patterns Into PHP?
If you programmed in Java, read Design Patterns: Elements of Reusable Object-Oriented Software and it changed your life, you may want to bring those same design patterns across to PHP. Some of them will be a good choice, but some of them will just be comfortable bad choices. They’re comfortable because you’re used to implementing and maintaining them, but they’re a bad choice because PHP provides you with better tools to get the job done.
The real trick – as with anything else in programming – is know when to use what.