mirror of
https://github.com/DesignPatternsPHP/DesignPatternsPHP.git
synced 2025-02-23 17:22:41 +01:00
Merge pull request #135 from bocharsky-bw/patch-1
Replace array storage with SplObjectStorage
This commit is contained in:
commit
7e707cc0fc
@ -36,11 +36,20 @@ class ObserverTest extends \PHPUnit_Framework_TestCase
|
||||
public function testAttachDetach()
|
||||
{
|
||||
$subject = new User();
|
||||
$this->assertAttributeEmpty('observers', $subject);
|
||||
$reflection = new \ReflectionProperty($subject, 'observers');
|
||||
|
||||
$reflection->setAccessible(true);
|
||||
/** @var \SplObjectStorage $observers */
|
||||
$observers = $reflection->getValue($subject);
|
||||
|
||||
$this->assertInstanceOf('SplObjectStorage', $observers);
|
||||
$this->assertFalse($observers->contains($this->observer));
|
||||
|
||||
$subject->attach($this->observer);
|
||||
$this->assertAttributeNotEmpty('observers', $subject);
|
||||
$this->assertTrue($observers->contains($this->observer));
|
||||
|
||||
$subject->detach($this->observer);
|
||||
$this->assertAttributeEmpty('observers', $subject);
|
||||
$this->assertFalse($observers->contains($this->observer));
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -20,9 +20,14 @@ class User implements \SplSubject
|
||||
/**
|
||||
* observers
|
||||
*
|
||||
* @var array
|
||||
* @var \SplObjectStorage
|
||||
*/
|
||||
protected $observers = array();
|
||||
protected $observers;
|
||||
|
||||
function __construct()
|
||||
{
|
||||
$this->observers = new \SplObjectStorage();
|
||||
}
|
||||
|
||||
/**
|
||||
* attach a new observer
|
||||
@ -33,7 +38,7 @@ class User implements \SplSubject
|
||||
*/
|
||||
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)
|
||||
{
|
||||
$index = array_search($observer, $this->observers);
|
||||
|
||||
if (false !== $index) {
|
||||
unset($this->observers[$index]);
|
||||
}
|
||||
$this->observers->detach($observer);
|
||||
}
|
||||
|
||||
/**
|
||||
|
Loading…
x
Reference in New Issue
Block a user