Mvc Confusion

Hi, I am new to Yii and have come from a background building simpler websites often using Drupal or Joomla and, though I feel I mostly ‘get’ the MVC design pattern, there are some things which I am unsure about the correct ‘mvc way’ and ‘Yii way’ to implement. Any insights anyone could offer would be very helpful.

The main stumbling block I have right now is probably best served with an example:

Say I am building an ecommerce site, I will likely have controllers for categories, products, pages, shopping process (checkout etc) which have a selection of different views depending on what the user is trying to do and, obviously, the controller and view can interact with the data model.

The part I find confusing is that, in this case I also have a persistent navigation which is built using product categories so needs to get that data from a model to render it. What is the right way to go about this? Should it be a widget? A partial view? What is the way to pass a model into a widget and should you? The same question could apply to the persistent shipping basket which needs data from products model so again I am getting confused about the right way to put these parts together.

I appreciate this is probably a really obvious thing but as I said, I’m not that familiar with MVC and just want to clear it up.

Thanks for any help.

I prefer using widgets.

So I do this:


<? $this->widget('MyWidget', array('data' => $mydata)); ?>

// here goes passing data----^^^^^^^^^^^^^^^^^^^^^^^^


class MyWidget extends CWidget {

    public $data; // !!!

    public function run() {

        $controller = $this->controller;

        $action = $controller->action;

        $items = ...; // get items depends on some condition

        $this->render('myWidget', array('items' => $items));



Thanks ORey, I hadn’t realised widgets could render view files which I think clears everything up, that and I think I’m starting to wrap my head around it, widgets seem like mini controllers which is exactly the kind of functionality I was looking for as the widgets need to be separate from the current controller.

So do you think a category tree menu or a shopping basket is a good fit for a widget?

Thanks again.



Yes - menus and any view that needs to be reused is a perfect fit for widgets. They are not mini controllers though - you cannot point a URL to a widget. Have a look at Yii breadcrumbs and menu.

Thanks, though there are a few references to widgets being “like” controllers and I think it is a good analogy, though they cannot be accessed by a URL they are accessed on a page in the same kind of way. A view requests a widget, the widget gets its data from a model and renders a view. That seems to make sense to me - maybe they are more like partial controllers like views have partial views - I don’t know.

You make a good point about looking at existing code to understand how they work, as this is what I did and it was very helpful. Thanks.