View Full Version : The Controller in MVC

08-27-2007, 04:02 PM

I've been checking out articles about the MVC design pattern recently, and tried to implement a very basic one myself. Everything has been going relatively smoothly with the models and the views, but I've got a few questions about the controller aspect. Hope someone here is willing to enlighten me. :)

First of all, one basic thing that isn't mentioned in any of the articles I've read concerns using multiple models on a page. I don't know if I've failed to grasp something here but it seems obvious that you sometimes have to use more than one model on a page. Say, your website's front page where you list users (using the User model) news items (using the News model) etcetera. All this info needs to come together in a single "view" so to speak.

So, first question, are you supposed to be able to use more than one model per page?

Now, if that is the case, I don't see how you can implement this using a single controller (index.php) which gets its info from the URL (as in, model=foo&method=bar) like some of the articles I've read does. Well I guess you could, but it would be a bit clunky.

However, other articles use a system where they have one controller for each view. Is this a better method?

08-27-2007, 05:35 PM
Having more than one model per page is absolutely fine, controller<-->model is certainly not one-to-one.

When using a 'Front Controller' (all requested routed through your 'index.php'), it doesn't mean that all the logic happens there. It's just left up to that part of the code to decide what gets done- which other functions are called, which classes are instantiated and so on. The (an) alterative, is to have each 'action' look after itself (so you'd have 'adduser.php', 'viewallusers.php' and so on, each doing just the one thing).

It's worth reading this thread over at Sitepoint, it contains a lot of questions and answers regarding the whole MVC thing- I'd reccomend reading it all though, as quite a few of the earlier posts are referenced and corrected/amended later on:

08-27-2007, 06:08 PM
Alright, so I can have more than one model, that's good to know. I'm going read through that thread tomorrow, thanks.

Without much thought going into it, would this be a valid way of doing things?

Each view is complemented by its own controller, which loads the necessary models. Index.php then includes the controller based on what the user puts in the URL field.


The above link would include the home controller, which in turn deals with models and views. Am I completely confused? :P

08-27-2007, 10:23 PM

if (isset($_GET['page'])) {
$safe_pages = array('home', 'about', 'etc');
$in_array = in_array($_GET['page'], $safe_pages);
if ($in_array) {
include ($_GET['page']'.php');
include (home.php);

this will include home.php if page isnt specified or in the array of safe pages they are allowed to view.