2013-02-06 57 views
4

我對MVC模式的結構感到困惑。模型如何更新MVC模式中的視圖?

在谷歌搜索的一些地方,我發現模型更新了訂閱該模型的所有視圖。模型如何以MVC模式更新視圖?

任何人都可以給我一個簡單和清晰的想法如何通過舉一個例子發生?

謝謝

回答

4

MVC有多種口味。這聽起來像你可能一直在閱讀關於supervising controller pattern,其中視圖觀察模型的變化。

我從你過去的問題和答案中看到你喜歡php。我不確定監督主持人在php中有多常見(我當然從未使用它,但有興趣知道其他人是否也這樣做)。在.Net應用程序(例如winforms)中,一個模型可以綁定到UI控件。通過訂閱模型事件來向視圖通知模型的更改。

總之,因爲我認爲這將是有趣的PHP嘗試我放在一起的例子:

<?php 

$input = array(2, 3, 4, 5, 6, 7, 8, 9, 10); 

$model = new model(1); 
$controller = new controller(
       $model, new view($model, 0), new view($model, 2) 
      ); 

$controller->doAction($input); 

class model { 
    //the model changed event 
    public $modelChangedEvent = array(); 
    private $val; 

    public function __construct($val) { 
    $this->val = $val; 
    } 

    public function setVal($val) { 
    $this->val = $val; 
    //raise the model changed event because the model state has changed 
    $this->raiseModelChangedEvent(); 
    } 

    public function getSquaredVal() { 
    return pow($this->val, 2); 
    } 

    private function raiseModelChangedEvent() { 
    foreach ($this->modelChangedEvent as $handler) 
     call_user_func($handler); 
    } 

} 

class view { 

    private $model; 
    private $decimalPlaces; 
    private $valueHistory = array(); 

    public function __construct($model, $decimalPlaces) { 
    $this->model = $model; 
    $this->valueHistory[] = $model->getSquaredVal(); 
    $this->decimalPlaces = $decimalPlaces; 
    //listen to the model changed event and call handler 
    $this->model->modelChangedEvent[] = array(
          $this, 
          'modelChangedEventHandler' 
          ); 
    } 

    public function showView() { 
    $formatted = array_map(
       array($this, 'getFormattedValue'), $this->valueHistory 
       ); 
    echo implode('<br/>', $formatted), '<br/><br/>'; 
    } 

    public function modelChangedEventHandler() { 
    $this->valueHistory[] = $this->model->getSquaredVal(); 
    } 

    private function getFormattedValue($val) { 
    return number_format($val, $this->decimalPlaces); 
    } 

} 

class controller { 

    private $model; 
    private $view1; 
    private $view2; 

    public function __construct($model, $view1, $view2) { 
    $this->model = $model; 
    $this->view1 = $view1; 
    $this->view2 = $view2; 
    } 

    public function doAction($input) { 
    foreach ($input as $val) $this->model->setVal($val); 
    $this->view1->showView(); 
    $this->view2->showView(); 
    } 

} 
?> 
+0

感謝您的幫助:) – Wearybands