MVC Best Practices – View Acquiring Data Directly from Model in Yii Framework

modelmvcviewyii

I'm using Yii for a few years and only right now I realized, that their demo application (empowered by CRUD auto-generation tool — Gii) seems to be breaking key MVC architecture pattern. I'd like to discuss this here.

As long as I've been using MVC (about four years), I was always told, that view should not acquire data directly from model. Every piece of text about MVC, I've read so far, was always underlining, that both view and models should be completely separate and the controller is the only element, that spins them together. If I need any model data in view (most often used mechanism) I should let my controller to retrieve it and feed view with it.

Correct me, if I'm wrong, but finding this question and an answer to it makes me sure, that I'm right: while it is technically possible, it should be avoided.

So, in terms of Yii, that would be:

$probes = Probes::model()->getAllProbesForCurrentUser;

$this->render('index', array
(
    'probes'=>$probes
))

(quite obvious, I think — controller retrieves data from model and renders view, feeding it with that model)

If all above is right, then how should I explain this:

<?php $this->widget('CGridView', array
(
    'id'=>'users-grid',
    'dataProvider'=>$model->search(),
    'columns'=>array
    (
        'name',
        'email',
        'level'
    )
)); ?>

(a widget placed in view acquires data directly from model)

What am I missing?

Best Answer

The array can also called a ViewModel, it is different from the Model because it carries the data the view needs while the Model represent the application business entities. For simple CRUD form they are likely to be identical. But for complex form, a ViewModel can be combined from many models.

Related Topic