Studyon Minte9.com
ZCE 5.3




Observer Pattern




<?php abstract class M9_Models_Base implements M9_Observer, M9_Subject { private $_observers = array(); //@Override public function attachObserver(M9_Observer $observer) { $this->_observers[] = $observer; } //@Override public function detachObserver(M9_Observer $observer) { $this->_observers[] = array_diff($this->observers, array($observer)); } //@Override public function notifyObservers() { foreach($this->_observers as $observer) { $observer->updateVars($this); // --- Look Here --- // } } //@Override public function updateVars(M9_Subject $subject) { foreach(get_object_vars($this) as $k=>$v) { if (isset($subject->$k)) { $this->$k = $subject->$k; // --- Look Here --- // } } } } interface M9_Observer { public function updateVars(M9_Subject $subject); } interface M9_Subject { public function attachObserver(M9_Observer $observer); public function detachObserver(M9_Observer $observer); public function notifyObservers(); } class M9_Models_Catg extends M9_Models_Base { public $userId = null; } class M9_Models_Catg_Article extends M9_Models_Base { public $userId = null; } class M9_Models_Catg_Video extends M9_Models_Base { public $userId = null; } // init models (userId = NULL) $catgModel = new M9_Models_Catg(); $catgArticleModel = new M9_Models_Catg_Article(); $catgVideoModel = new M9_Models_Catg_Video(); // change user in catgModel $catgModel->userId = 10; // attach observers to catgModel $catgModel->attachObserver($catgArticleModel); // --- Look Here --- // $catgModel->attachObserver($catgVideoModel); // notify the observers Models $catgModel->notifyObservers(); echo $catgArticleModel->userId; // 10 echo $catgVideoModel->userId; // 10