-1

I have a problem with PHP/MVC. This is my index controller.

<?php
class Index extends Controller {
    function __construct() {
        parent::__construct();
    }
    function index() {
        $this->view->render('header');
        $this->view->render('index/index');
        $this->view->render('footer');
    }
    public function test(){
        $this->model->test();
    }
?>

And this, index model.

<?php
class Index_Model extends Model{
    public function __construct()    {
        parent::__construct();
    }
    public function test()    {
        return $this->db->select('SELECT text FROM test');
    }
}
}

How can I use this in "index view"?

  • That would go against the whole concept of MVC. Is there a reason why you can't call the necessary methods in the initial controller in the first place? (assuming you mean run through the controller and load the views, then for some reason have the view call back to the controller in a way other than some ajax request) – Kai Qing Jan 31 '14 at 02:01
  • 1
    You might find [this post](http://stackoverflow.com/a/16596704/727208) helpful. Also, model is **not a class** and it definitely is **not a DB abstraction** . Model is a layer, that contains various classes and encompasses all of the business logic within the application. – tereško Jan 31 '14 at 06:07

1 Answers1

1

Of course you can call controller and model methods from your views (if it wasn't possible then you'd need to put EVERYTHING in your view). The idea of MVC isn't complete separation (as some people wrongly think) but separation of the logic. This means that it is fine to pass data between the different parts of the MVC arch; the idea is that you want to try to make sure that the logic in each part is logic that is appropriate for that part.

Many people will over complicate this in search of some ideal which is just silly. I would get rid of the controller method all together and reference the model method directly in the view if all you are doing is grabbing some data to be displayed in the view. There is no reason to waste time and effort passing these results to the controller just to be passed back to the view. You will thank me for this advice once you make a truly large site and look at all of the effort you would have spent doing that (and then later maintaining all of it).

My philosophy is that a controller should be used for just that (controlling the application logic). If you want to display a sidebar with a list of the most recent post that has NOTHING to do with the controller so it shouldn't add any code to it. Save yourself some headache and call the model from the view. In the end your code is going to make more sense if you do.

In response to your question: You cannot use your controller method in the view because it doesn't return anything.

krowe
  • 2,129
  • 17
  • 19