Repository navigation
The Observer Pattern
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.
- Create a class that
extendstheEventclass in theEONConsulting\PHPStencil\Eventsnamespace. - Create your observer that
implementstheSplObserverclass that is part of the SPL (Standard PHP Library)
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.
Create your observer class. Here you need to do 2 things.
- Implement SplObserver using the following command:
implements \SplObserver - Make sure you have a method called
updatethat has a parameter of\SplSubject $event- you can label this$eventvariable whatever you like - as long as it has the typehint ofSplSubject.
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();