Chapter 17. Strategy Pattern

The worst few months of my career were completely unavoidable. I tackled a big project with a large code base. New requirements kept popping up, and I did what any inexperienced junior programmer would do: I just added on to my objects. My classes started becoming monolithic. I kept obliterating my unit tests. As luck would have it, I was just learning about object inheritance in PHP. From then on, I started creating more but smaller classes, each extending others to add additional functionality. My problem went from having a few single giant classes to having way too many smaller classes to keep track of. The issues continued. If it wasn't the sheer size of the list of objects in my repository, it was the convoluted naming scheme I had to develop to keep those objects organized. I found that there was also a lot of bloat in my classes. There were methods that were not called in most instances of the class. My next refactoring step involved removing some of this logic from these base classes and adding it to individual classes that would only be created when need be. This is where the Strategy Design Pattern really shines.

Name: Strategy

The Strategy Design Pattern helps architect an object that can make use of algorithms in other objects on demand in lieu of containing the logic itself.

Get Professional PHP Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.