PHP观察者模式

时间:2014-04-25 13:53:28

标签: php design-patterns

我在zend中使用了一个简单的php观察者模式。从控制器通知到特定的观察者。在该输入参数是id,返回类型是array。仍然在控制器中给对象作为返回响应。主题如下:

<?php

class Newsubject implements Subject{

    public $observers = array();

    function __construct() { }

    public function getdata(id){

        $this->id = id;

        $this->notify(id);
    }

    public function attach(Observer $obsever)
    {
        $id = spl_object_hash($obsever);
        $this->observers[$id] = $obsever;
    }

    public function detach(Observer $obsever)
    {
        $id = spl_object_hash($obsever);
        unset($this->observers[$id]);
    }

    public function notify(id)
    {
        foreach($this->observers as $obs)
        {
            $obs->update(id);
        }
    }
}
?>

观察者如下:

<?php

class Newobserver implements Observer{

    public function update($id)
    {
        $modelmethod = new Modelmethod();

        $modelmethod = $modelmethod->getdata($id);
        //which is an array
        return $modelmethod;
    }
}
?>

来自控制器的呼叫:

$subject = new Newsubject();
$subject->attach(new Newobserver());
$id = 2;
$returnarray->getdata($id);

print_r($returnarray);

输出:

  

Newsubject Object([observers] =&gt;数组([00000000243330360000000069e80d68] =&gt; Newobserver)

它应该返回array.Any建议。 感谢。

1 个答案:

答案 0 :(得分:0)

让堆栈跟踪流程 -

$returnarray->getdata($id);

以上电话getdata($id)致电$this->notify(id);

notify()具有observers[]数组,但此数组的每个键都有对象。

 foreach($this->observers as $obs)       /*$this->observers is array*/
 {
     $obs->update(id);        /*but $obs seems to be an object - individually*/
 }

例如:     observers = array ( Object (...), Object (...), Object (...), );

看看它。