Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do MVC components fit together?

I've seen a number of examples of ways MVC components fit together on the web.


The Controller retrives data from the Model and passes it to the View

This seems a bit verbose and messy.

$model = new Model;
$view = new View;
$view->set('foo', $model->getFoo());
$view->display();

The Controller passes the Model to the View

What if the View needs data from multiple Models?

$model = new Model;
$view = new View($model);
$view->display(); //View takes what is needed from the Model

The Controller passes the View to the Model

$view = new View;
$model = new Model($view);
$view->display(); //Model has told the View what is needed

Which of these is the "best" way to go about things? If none, what is?

like image 946
etheros Avatar asked Dec 29 '22 13:12

etheros


2 Answers

The Controller retrives data from the Model and passes it to the View

As you said it's verbose and messy. But that's the most appropriate solution with the philosophy of MVC.

The Controller passes the Model to the View

Seems valid too. However it'll require for the view to ask for some model method. Which is not really in the spirit of MVC. Your view should only render the datas that are provided to it, without caring about the context.

The Controller passes the View to the Model

Forget that one. Here it is messy.

like image 121
Damien MATHIEU Avatar answered Jan 18 '23 04:01

Damien MATHIEU


The answer is self evident if you consider that the 'model' is the central artifact (potentially used across applications), and that a 'view' may (or may not) be aware of the specific model but it is (by definition) a 'view' of a (potentially abstract) model and again, potentially usable across applications. The 'controller' is managing interactions and is the most application specific element of the pattern, so it definitively needs to know about model and view details.

If the view is specific to a given model, you can use option 2. If the view is for an abstract model (and you can use it to display info from a set of models), you use option 1.

Option 3 is simply wrong.

like image 32
alphazero Avatar answered Jan 18 '23 04:01

alphazero