An observer design pattern is a solution for loosely coupled objects so that they can work together. In PHP, you can easily implement this using only two classes .
Basically, you have a topic that can notify and update the list of observers about state changes.
The problem I'm trying to solve is to know how the handler warns observers about the different states of the object they are viewing.
For example, suppose we have a file upload class to which we attach a logging class, a websockets class, and a resize class. Each of these watch classes wants to know about various events during the boot process.
This file upload class can have three places where it needs to notify listeners that something has happened.
- Error loading (alert logging class)
- Download Success (Web Class Alert Class)
- Download success and image file (image resizing class for warning)
This is a very simple example, but how do you handle several events that different observers may know about? A single call to notifyObservers () will not be enough, as each observer should know what he is notified about.
One thought is that I can indicate with a call what type of event is being observed:
$this->notifyObservers('upload.error', this);
However, this would mean that I have to add custom switching to the observers themselves in order to know how to handle different events.
function observe($type, $object)
{
if($type === 'upload.error') $this->dosomething();
elseif($type === 'something.else') $this->otherthing();
...etc...
}
, , .
, - , - , , , () .