mirror of
https://github.com/DesignPatternsPHP/DesignPatternsPHP.git
synced 2025-08-01 20:50:15 +02:00
PHP7 Observer
This commit is contained in:
@@ -3,60 +3,42 @@
|
||||
namespace DesignPatterns\Behavioral\Observer;
|
||||
|
||||
/**
|
||||
* Observer pattern : The observed object (the subject).
|
||||
*
|
||||
* The subject maintains a list of Observers and sends notifications.
|
||||
* User implements the observed object (called Subject), it maintains a list of observers and sends notifications to
|
||||
* them in case changes are made on the User object
|
||||
*/
|
||||
class User implements \SplSubject
|
||||
{
|
||||
/**
|
||||
* user data.
|
||||
*
|
||||
* @var array
|
||||
* @var string
|
||||
*/
|
||||
protected $data = array();
|
||||
private $email;
|
||||
|
||||
/**
|
||||
* observers.
|
||||
*
|
||||
* @var \SplObjectStorage
|
||||
*/
|
||||
protected $observers;
|
||||
private $observers;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->observers = new \SplObjectStorage();
|
||||
}
|
||||
|
||||
/**
|
||||
* attach a new observer.
|
||||
*
|
||||
* @param \SplObserver $observer
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function attach(\SplObserver $observer)
|
||||
{
|
||||
$this->observers->attach($observer);
|
||||
}
|
||||
|
||||
/**
|
||||
* detach an observer.
|
||||
*
|
||||
* @param \SplObserver $observer
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function detach(\SplObserver $observer)
|
||||
{
|
||||
$this->observers->detach($observer);
|
||||
}
|
||||
|
||||
/**
|
||||
* notify observers.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function changeEmail(string $email)
|
||||
{
|
||||
$this->email = $email;
|
||||
$this->notify();
|
||||
}
|
||||
|
||||
public function notify()
|
||||
{
|
||||
/** @var \SplObserver $observer */
|
||||
@@ -64,21 +46,4 @@ class User implements \SplSubject
|
||||
$observer->update($this);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ideally one would better write setter/getter for all valid attributes and only call notify()
|
||||
* on attributes that matter when changed.
|
||||
*
|
||||
* @param string $name
|
||||
* @param mixed $value
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __set($name, $value)
|
||||
{
|
||||
$this->data[$name] = $value;
|
||||
|
||||
// notify the observers, that user has been updated
|
||||
$this->notify();
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user