Reputation: 17000
(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 div
s with lots of nested elements.
But what is the best practice to send collection of elements to View?
Upvotes: 1
Views: 97
Reputation: 11122
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.
Upvotes: 3