Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Going from the Controller to the View

I am working on creating my own very simple MVC and I am brainstorming ways to go from the controller to the view. Which involves sending variables from a class to just a plain old PHP page.

I am sure that this has been covered before, but I wanted to see what kind of ideas people could come up with.

//this file would be /controller/my_controller.php

class My_Controller{

   function someFunction(){

  $var = 'Hello World';
  //how do we get var to our view file in the document root?
  //cool_view.php

   }

}
like image 962
Mike Avatar asked Oct 14 '22 01:10

Mike


2 Answers

Some kind of hashtable is a good way to do that. Return your variables as association array which will fill all the gaps in your view.

like image 154
Łukasz W. Avatar answered Oct 31 '22 14:10

Łukasz W.


Store your variables as a property in your controller object, then extract them when rendering

class My_Controller {

    protected $locals = array();

    function index() {
        $this->locals['var'] = 'Hello World';
    }

    protected function render() {
        ob_start();
        extract($this->locals);
        include 'YOUR_VIEW_FILE.php';
        return ob_get_clean();
    }
}

You can define those magic __get and __set methods to make it prettier

$this->var = 'test';
like image 33
Sean Huber Avatar answered Oct 31 '22 13:10

Sean Huber