PhpRiot
News Archive
PhpRiot Newsletter
Your Email Address:

More information

PHPMaster.com: Understanding the Observer Pattern

Note: This article was originally published at PHPDeveloper on 24 February 2012.
PHPDeveloper

PHPMaster.com has a new tutorial looking at another popular design pattern, the Observer pattern, and sharing some example code putting it to use. (Their other design pattern articles include ones on command and factory patterns).

In this article I'll show you how to implement the Observer Pattern. You'll learn how various classes in the pattern relate to one another as subject and observers, how the subject notifies observers of a change in its state, and how to identify scenarios where it would be suitable to use the Observer Pattern in your own code.

The introduce the pattern by using an abstract "Observer" and "Subject" (that defines "attach", "detach", "getState", "setState", "notify" and "getObservers" methods) observer classes to coordinate the attached classes. They extend these classes with "Auth" and "Auth_ForumHook" show how to attach the "Auth_ForumHook" classes to the main "Auth" observer manager and change the state of the observer to notify it of an update.

You can find a more detailed explanation of the Observer pattern on Wikipedia.