Observer mode for PHP, there are several built-in interface implementations, and the associated patterns, respectively, are Splsubject
Subobserver and Splobjectstoarge, compared to UML class diagrams, I prefer to explain the phenomenon in a more understandable diagram, as shown below.
The Observer stores all the object mappings of the observer by mapping the object, and then, when the observer changes, loops over the image, notifying all observers
, directly on the code.
Subject (observed) class:
/**
* @package: Observer mode
* The so-called observer, the popular point of the
subject (observed A) splsubject
storage container (Observer mapping table) Splobjectstorage
Observer B1,b2,b3 ... Splobserver
A a period of change, b1,b2,b3 ... will receive the corresponding notification
///------------subject of the Observer
class Subject implements Splsubject
{
private $observers;
Private $data;
Public Function Setstorage ()
{
$this->observers = new Splobjectstorage ();
}
Public function Attach (Splobserver $observer)
{
$this->observers->attach ($observer);
}
Public Function Detach (splobserver $observer)
{
$this->observers->detach ($observer);
}
Public function Notify ()
{
foreach ($this->observers as $observer) {
$observer->update ($this);
}
}
Public Function SetData ($data)
{
$this->data = $data;
}
Public Function GetData ()
{return
$this->data;
}
}
Observed by:
---------------Observer
//---------that is to say, every observer can be notified to
class Observer implements as long as it implements Splobserver and implements the method update. Splobserver
{
private $name = ';
Public function __construct ($name)
{
$this->name = $name;
}
Public Function Update (Splsubject $subject)
{
echo $this->name. ":";
Var_dump ($subject->getdata ());
}
Call:
Instance using
$A = new Subject ();
$A->setstorage ();
$B 1 = new Observer (' B1 ');
$B 2 = new Observer (' B2 ');
$B 3 = new Observer (' B3 ');
$A->attach ($B 1);
$A->attach ($B 2);
$A->attach ($B 3);
$A->setdata (' 123 ');
$A->notify ();
$A->detach ($B 2);
$A->setdata (' 456 ');
$A->notify ();
Call Result:
B1:string (3) "123"
B2:string (3) "123"
B3:string (3) "123"
B1:string (3) "456"
B3:string (3) "456"
You can see that each object that exists in the mapping object receives a corresponding notification. In fact, specific ideas, we should not only be limited to
PHP gives Splobjectstorage storage that we can extend to Redis and other, Splsubject and Splobserver too, as long as
The implementation of the observer can obtain each observer, and can call the corresponding observer notification method, somewhat similar to the timing of Message Queuing push,