Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top