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 #67. Observe Your Objects

Use the Observer pattern to loosely couple your objects.

Loose coupling is critical to any large-scale project, but few people actually understand what the term really means. Have you ever made a small change in a project, and it seems that as a result, almost everything else has to change as well? This occurs all too often because of tight coupling among the modules in the program. Each module relies on the exact state or function of several other modules. When one fails, they all fail. When one changes, they all must change.

The Observer pattern loosens up the bonds among objects by providing a simpler intra-object contract. An object allows itself to be observed by providing a mechanism where objects can register with it. When the observed object changes, it notifies the observing objects through a notification object. The observed object does not care how or why it is being observed, nor does it even know what types of objects are observing it. Further, the observers usually don't care why or how the object is changing; all they are looking for is a change.

A classic example is the code in a dialog observing the state of a checkbox. The checkbox doesn't care if it's being observed by one object or a thousand objects. It simply sends out a message when its state changes. In the same way, the dialog doesn't care how the checkbox is implemented; it only cares about the box's state and about being notified when that state changes.

In this hack, I'll demonstrate ...

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