Skip to content

The Observer Pattern

Josh 'VaMoose' harington edited this page Dec 1, 2016 · 1 revision

The Observer Pattern

Introduction

The observer pattern is very useful, and you will use it a lot for certain tasks across all types of applications. An observer, is an object (called the subject) that maintains a list of all of its dependents (called observers).

If a state change occurs to the main object, it will notify the dependents by calling one of their methods.

To make use of this pattern, we have made it easy for you. There are 2 steps.

  1. Create a class that extends the Event class in the EONConsulting\PHPStencil\Events namespace.
  2. Create your observer that implements the SplObserver class that is part of the SPL (Standard PHP Library)

Step 1 - Extend Event

Create your normal class that will hold your object. All you need to do is extend the Event class. If you have a constructor, do not overwrite the parent constructor (the constructor in the Event class) by calling parent::__construct(); at the top of your constructor.

Step 2 - Implement \SplObserver

Create your observer class. Here you need to do 2 things.

  1. Implement SplObserver using the following command: implements \SplObserver
  2. Make sure you have a method called update that has a parameter of \SplSubject $event - you can label this $event variable whatever you like - as long as it has the typehint of SplSubject.

Using the pattern

Now, create the object like you would any other.


$event = new ExampleClass;

Then we need to attach the observers you wish to call.


$event->attach(new ObserverClassOne);
$event->attach(new ObserverClassTwo);
$event->attach(new ObserverClassThree);

And finally, when you would like to call the observers, go ahead and execute the following line of code:


$event->notify();

Clone this wiki locally