mirror of
https://github.com/DesignPatternsPHP/DesignPatternsPHP.git
synced 2025-08-02 13:07:27 +02:00
Replace array storage with SplObjectStorage
If you already use SPL interfaces in your example, maybe better to use `SplObjectStorage` too instead of `array` to store observers with `attach` and `detach` convenient methods? What do you think?
This commit is contained in:
@@ -20,9 +20,14 @@ class User implements \SplSubject
|
|||||||
/**
|
/**
|
||||||
* observers
|
* observers
|
||||||
*
|
*
|
||||||
* @var array
|
* @var \SplObjectStorage
|
||||||
*/
|
*/
|
||||||
protected $observers = array();
|
protected $observers;
|
||||||
|
|
||||||
|
function __construct()
|
||||||
|
{
|
||||||
|
$this->observers = new \SplObjectStorage();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* attach a new observer
|
* attach a new observer
|
||||||
@@ -33,7 +38,7 @@ class User implements \SplSubject
|
|||||||
*/
|
*/
|
||||||
public function attach(\SplObserver $observer)
|
public function attach(\SplObserver $observer)
|
||||||
{
|
{
|
||||||
$this->observers[] = $observer;
|
$this->observers->attach($observer);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -45,11 +50,7 @@ class User implements \SplSubject
|
|||||||
*/
|
*/
|
||||||
public function detach(\SplObserver $observer)
|
public function detach(\SplObserver $observer)
|
||||||
{
|
{
|
||||||
$index = array_search($observer, $this->observers);
|
$this->observers->detach($observer);
|
||||||
|
|
||||||
if (false !== $index) {
|
|
||||||
unset($this->observers[$index]);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
Reference in New Issue
Block a user