1

(Using PHP style code)

Lest imagine we have Controller within which we have array of string data:

class Controller {
    private $data = array('a', 'b', 'c', 'd', 'e');
}

Now Controller have to pass that data to View to produce lets say such HTML:

<p>a</p>
<p>b</p>
<p>c</p>
<p>d</p>
<p>e</p>

Question:

Should we pass all the array to View for it to process array data within itself like:

class Controller {
  private $data = array('a', 'b', 'c', 'd', 'e');
  function __construct($data) { // Assigns data array to view
    $view = new View;
    $view->produceHTML($data)
  }
}

class View {
  public function produceHTML($data) {
    foreach($data as $value) {
      echo "<p>$value</p>" . PHP_EOL; // PHP_EOL - PHP Predifined constant (End Of Line)
    }
  }
}

Or we should define different Views for every element like:

class Controller {
  private $data = array('a', 'b', 'c', 'd', 'e');
  function __construct($data) { // Assigns data array to view
    $view = new View;
    $view->produceHTML($data)
  }
}

class View {
  public function produceHTML($data) {
    foreach($data as $value) {
      $this->produceP($value);
    }
  }

  private function produceP($value) {
    echo "<p>$value</p>" . PHP_EOL;
  }
}

Using short data values is just for the example. In most cases I've encountered much more complex Views which produce big divs with lots of nested elements.

But what is the best practice to send collection of elements to View?

1
  • are you going to build a framework? Commented Sep 6, 2012 at 18:50

1 Answer 1

3

In proper MVC, the controller shouldn't "send" any data to the view. The view is an active layer of the application which should retrieve data from the model layer. The controller should only change the state of the model, but shouldn't retrieve any data.

Sign up to request clarification or add additional context in comments.

2 Comments

:) So in other words you choose my first variant - View itself should process all the output, retrieved all data from the Model layer?
Well, no. In your first variant, you're passing data to the view from the controller. That fits more in line with an MVP-style pattern.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.