0

Example:

I have models Post, Comment and User. I want to display the recent posts, comments and users on the home page.

Which controller should be used?

Can a single controller query multiple models, even if they are not related?

Who is responsible for making the data available to the view?

Can a view ask a model for data directly?

tereško
  • 58,060
  • 25
  • 98
  • 150
Schrute
  • 711
  • 7
  • 15

1 Answers1

2

Which controller should be used?

The controller that is the most logical domain for whatever you try to display. In your case it's the articles controller. Because you want to view an article and the article has many comments and an user belongs to a comment.

Can a single controller query multiple models, even if they are not related?

Yes, lookup Controller::loadModel(). But the prefered way to access data is through associations.

Who is responsible for making the data available to the view?

The controller sets it to the view, lookup Controller::set().

Can a view ask a model for data directly?

No. Technically you can load a model instance into a view but this will break the MVC design pattern and result in not really nice to understand and maintain code. DON'T do it.

floriank
  • 25,546
  • 9
  • 42
  • 66
  • I think my example wasn't very good. What I'm struggling with is how to deal with cases where I don't really have a clear dominant controller for the page. Imagine 3 completely separated models. Do I choose one randomly to render the home page? Or do I create a HomePageController or something like that? Thanks for answering! – Schrute Nov 12 '13 at 23:36
  • Yes, if your models are not related at all then you can create a controller of your preference, then load the models using Controller::loadModel() like @burzum said. – Guillermo Mansilla Nov 13 '13 at 04:45