Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC: Why bother "sending" data to the View

I'm very new to MVC, and so I've been scouring the net in an attempt to build my own framework to get a real understanding on how the whole concept works.

Anyway, almost all tutorials out there that deal with MVC always seem to assign data that needs to be displayed in the view to an intermediary variable that is THEN used in the view.

My question is, why bother with that extra step?

Most MVC implementations end up including the view WITHIN the controller... so if that's the case, why waste time/memory/cpu cycles to create an intermediary variable/array that is then passed to the View when the View ends up being included with the controller at the end.

Would it not make more sense to simply use the Controller variables directly in the View itself?

Here's a code example to hopefully clarify what I mean:

class News_Controller 
{

public function main(array $getVars)
{
    $newsModel = new News_Model;

    //get an article
    $article = $newsModel->get_article($getVars['article']);

    //create a new view and pass it our template name
    $view = new View_Model($this->templateName);

    //assign article data to view
    $view->assign('title' , $article['title']);
    $view->assign('content' , $article['content']);
    $view->render();
}

The render function is basically just an include to bring the View into the Controller to be displayed down the chain. If that's what's going on, one could simply use $article directly in the View rather than go through the hassle of assigning variables to the View.

like image 771
Brownbay Avatar asked Dec 13 '22 08:12

Brownbay


1 Answers

Keep in mind that PHP copies on write. So there is no major performance hit to a simple variable assignment.

As already mentioned, scope is a big issue here. The view is a separate entity from the controller and doesn't have access to its data. Of course, you could pass an instance of the controller to the view, but that's creating an unnecessarily too strict of coupling between the two. The view should be able to work independent of the controller.

So by explicitly assigning data to the view you decouple the two. You will tend to write better and cleaner code as a result.

Second, the process of assigning data to a view could do some data sanitizing or other extra work. For instance, in my framework, I consider all data passed to an HTML view as unsafe. When data is passed to the view (unless explicitly marked as safe) it is encoded via htmlspecialchars.

Finally, you can always assign objects or arrays to the view:

$view->assign('article', $article);

If you do this you generally don't need to assign very much stuff. (And if you do, perhaps your page is doing too many different things.)

like image 69
Matthew Avatar answered Dec 24 '22 11:12

Matthew