From db7dab5b0d13a85d5d4b1f9735934aee88865568 Mon Sep 17 00:00:00 2001 From: Bocharsky Victor Date: Wed, 27 May 2015 21:37:19 +0300 Subject: [PATCH] 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? --- Behavioral/Observer/User.php | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/Behavioral/Observer/User.php b/Behavioral/Observer/User.php index 013f194..a441038 100644 --- a/Behavioral/Observer/User.php +++ b/Behavioral/Observer/User.php @@ -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); } /**