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 ...

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

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.