Object-oriented – Can you call any php model class in an MVC from the controller

mvcobject-orientedPHP

I'm creating a simple MVC at the moment and am wondering if it's 'correct' to be able to call any model class directly from the controller to get the data to send to the view?

I have the following folder structure:

.htaccess
index.php
/controller
/model
/templates

I also have the needed model classes within the /model folder, at the moment I've tried playing with a /model/model.class.php to try and build all parts of the site but it's already starting to become huge and I think it might be better to completely cut it out.

I'm thinking the better approach is to use:

elseif($_GET['type'] == "Profile") {
    $profile = new thread($userId);
    $comments =  $profile->getComments();
    require "templates/profile.php";
}

The above is a brief example but is that how a controller could/should/might look or was the first approach better or am I completely missing the point of the model and controller communication?

Best Answer

I'm not sure I completely understand your question, so I apologize if I misinterpreted it.

A controller may have an access to any model of your application. There is no reason to assign a set of models to every controller, and to restrict the access to those models only.

Now, a model is linked to a view (if the view requires a model). If the view HomePage expects the model RecentPosts, the controller has to provide the initialized RecentPosts model to the view.

It's up to the controller to decide where and when to call a view and to pass to it a model this view requires.

Related Topic