How does the model update the view in the MVC template?

I have a confusion in the structure of the MVC pattern.

In some places, during a google search, I found that the model updates all the views that are subscribed to this model. How does the model update the view in the MVC template?

Can someone give me a simple and clear idea about how this happens, giving an example?

thank

+5
source share
1 answer

MVC comes in a variety of flavors. It looks like you may have read about the control pattern of the controller , in which the view observes changes in the model.

, 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();
   }

}
?>
+4

All Articles