mirror of
https://github.com/DesignPatternsPHP/DesignPatternsPHP.git
synced 2025-08-06 23:16:33 +02:00
cs
This commit is contained in:
@@ -10,49 +10,57 @@ namespace DesignPatterns\Observer;
|
||||
*/
|
||||
class User implements \SplSubject
|
||||
{
|
||||
|
||||
protected $_data = array();
|
||||
|
||||
/**
|
||||
* user data
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_observers = array();
|
||||
protected $data = array();
|
||||
|
||||
/**
|
||||
* observers
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $observers = array();
|
||||
|
||||
/**
|
||||
* attach a new observer
|
||||
*
|
||||
* @param \SplObserver $observer
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function attach(\SplObserver $observer)
|
||||
{
|
||||
$this->_observers[] = $observer;
|
||||
$this->observers[] = $observer;
|
||||
}
|
||||
|
||||
/**
|
||||
* detach an observer
|
||||
*
|
||||
* @param \SplObserver $observer
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function detach(\SplObserver $observer)
|
||||
{
|
||||
$index = array_search($observer, $this->_observers);
|
||||
$index = array_search($observer, $this->observers);
|
||||
|
||||
if (false !== $index) {
|
||||
unset($this->_observers[$index]);
|
||||
unset($this->observers[$index]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* notify observers
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function notify()
|
||||
{
|
||||
/** @var SplObserver $observer */
|
||||
foreach ($this->_observers as $observer) {
|
||||
foreach ($this->observers as $observer) {
|
||||
$observer->update($this);
|
||||
}
|
||||
}
|
||||
@@ -61,17 +69,16 @@ class User implements \SplSubject
|
||||
* Ideally one would better write setter/getter for all valid attributes and only call notify()
|
||||
* on attributes that matter when changed
|
||||
*
|
||||
* @param $name
|
||||
* @param $value
|
||||
* @param string $name
|
||||
* @param mixed $value
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __set($name, $value)
|
||||
{
|
||||
$this->_data[$name] = $value;
|
||||
$this->data[$name] = $value;
|
||||
|
||||
// notify the observers, that user has been updated
|
||||
$this->notify();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
@@ -17,7 +17,6 @@ namespace DesignPatterns\Observer;
|
||||
*/
|
||||
class UserObserver implements \SplObserver
|
||||
{
|
||||
|
||||
/**
|
||||
* This is the only method to implement as an observer.
|
||||
* It is called by the Subject (usually by SplSubject::notify() )
|
||||
@@ -28,5 +27,4 @@ class UserObserver implements \SplObserver
|
||||
{
|
||||
echo get_class($subject) . ' has been updated';
|
||||
}
|
||||
|
||||
}
|
||||
|
Reference in New Issue
Block a user