O'Reilly logo

Learning PHP Design Patterns by William Sanders

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 12. The Flexibility of the Strategy Design Pattern

Victorious warriors win first and then go to war, while defeated warriors go to war first and then seek to win.

Sun Tzu

In preparing for battle I have always found that plans are useless, but planning is indispensable.

Dwight D. Eisenhower

All I had done was to improve on their strategy, and it was the beginning of a very important lesson in life—that anytime you find someone more successful than you are, especially when you’re both engaged in the same business—you know they’re doing something that you aren’t.

Malcolm X

Encapsulating Algorithms

One of the ongoing tasks in using PHP with MySQL is writing algorithms for the different kinds of requests made of a MySQL application. Typical requests include creating tables or entering, selecting, changing, and deleting data. The algorithms for these different requests are simple or complex depending on both the complexity of the request and of the table.

One of the main principles of design patterns is to encapsulate what varies. With several different algorithms for different kinds of requests sent to a PHP class that handles these MySQL requests, the variation is clearly the algorithms. The variations may be small or great, but using the Strategy design pattern, we can greatly simplify the process.

Generally, with design patterns, the question is “What causes redesign?” Then, we proceed to avoid those things that force redesign. But what if we instead think of a way to make changes ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required