O'Reilly logo

PHP Hacks by Jack D. Herrington

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

Hack #74. Build Extensible Processing with Chains

Use the Chain of Responsibility pattern to create a Plug and Play (PnP) processing framework in your code.

Watching football with programmers is fun. Even in the fourth quarter, when the game is 33 to 7 with 1:30 to go, you still get a range of options when you ask who is going to win the game. That's because programmers are trained to think of every potential situation, no matter how unlikely (and generally ludicrous). And I've found that most programmers, including myself, hate closing the door on any question. It's always better to write code that handles 100 possible scenarios, even when your manager swears up and down there will only ever be one.

That's why I think the Chain of Responsibility pattern is so appealing. Imagine walking into a room full of people with a box of donuts. You flip open the box and pull out a jelly donut. One by one you ask people, "You want a jelly donut?" until you find someone that does. Then you continue with your varied box of donut flavors until the box is empty.

That's the Chain of Responsibility pattern; each person in the room registers himself in advance with you, the donut vendor. Then, as new donuts come in, you see who wants them by looking through your list of registered people. The advantage is that you, as the vendor, don't care about how many people want donuts; you don't even care what they do with the donuts. You just manage the registry and the vending.

In this hack, I'll write some ...

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