Mike Moore
Mike Moore

Reputation: 7468

PHP MVC question

Given a Controller class and a View class, is it better for the controller to directly assign values to view properties or, is it better to assign values to properties in the controller and then copy those properties to the view when ready to display it?

Example Model Class

class Model
{
  public $propertyA;
  public $propertyB;
}

Example Controller class:

class Controller
{
  protected $view;
  protected $model;

  public function __construct()
  {
    $this->model = new Model();

    $this->view = new View();
    $this->prepareData();
    $this->initView();
  }

  protected function prepareData()
  {
    $this->model->propertyA = 'This is property A.';
    $this->model->propertyB = 'This is property B.';        
  }

  protected function initView()
  {
    $this->view->model = $this->model;
    $this->view->display();
  }
}

Example View class:

class View
{
  public $model;

  public function display()
  {
    echo "propertyA = $this->model->propertyA";
    echo "propertyB = $this->model->propertyB";
  }
}    

Sorry, I was tired. I do use a model, so please reconsider your answers with this in mind.

Upvotes: 2

Views: 205

Answers (2)

Benbob
Benbob

Reputation: 14234

The view shouldn't be setting up variables unless they are related to the presentation. It's best to put static variables in a config file anyway.

copy those properties to the view

Rather than setting variables in the view why don't you just construct the view with a reference to the controller. That should save you from writing a lot of boiler plate code.

Class Controller() {
  $this->something = 'abc';
  function __construct() {
    $this->display();
  }
  function display() {
    $this->view = new View($this);
  }
}

Class View() {

  function View(&$controller) {
    $this->controller = $controller;
    print $this->controller->something;
  }

}

Edit: I like Romain Hippeau's answer a lot more than my own. You should pass the model into the view.

Upvotes: 2

Romain Hippeau
Romain Hippeau

Reputation: 24375

The data should only be in one place. If not when things get complicated it is hard to sync the different places you have the data. In MVC you have a model and that is where the data should be. Pass the Model into the View and have the view display that.

Here is a simple explanation: http://en.wikipedia.org/wiki/Model%E2%80%93View%E2%80%93Controller or here for those that do not like Wikipedia: http://ootips.org/mvc-pattern.html

The model can be as simple as a class with the properties in it.

Upvotes: 5

Related Questions