Search code examples
phpmodel-view-controllerview

Render a view in PHP


I am writing my own MVC framework and has come to the view renderer. I am setting vars in my controller to a View object and then access vars by echo $this->myvar in the .phtml script.

In my default.phtml I call the method $this->content() to output the viewscript.

This is the way I do it now. Is this a proper way to do that?

class View extends Object {

    protected $_front;

    public function __construct(Front $front) {
        $this->_front = $front;
    }

    public function render() {                
        ob_start();
        require APPLICATION_PATH . '/layouts/default.phtml' ;            
        ob_end_flush();
    }

    public function content() {
        require APPLICATION_PATH . '/views/' . $this->_front->getControllerName() . '/' . $this->_front->getActionName() . '.phtml' ;
    }

}

Solution

  • Here's an example of how i did it :

    <?php
    
    
    class View
    {
    private $data = array();
    
    private $render = FALSE;
    
    public function __construct($template)
    {
        try {
            $file = ROOT . '/templates/' . strtolower($template) . '.php';
    
            if (file_exists($file)) {
                $this->render = $file;
            } else {
                throw new customException('Template ' . $template . ' not found!');
            }
        }
        catch (customException $e) {
            echo $e->errorMessage();
        }
    }
    
    public function assign($variable, $value)
    {
        $this->data[$variable] = $value;
    }
    
    public function __destruct()
    {
        extract($this->data);
        include($this->render);
    
    }
    }
    ?>
    

    I use the assign function from out my controller to assign variables, and in the destructor i extract that array to make them local variables in the view.

    Feel free to use this if you want, i hope it gives you an idea on how you can do it

    Here's a full example :

    class Something extends Controller 
    {
        public function index ()
        {
        $view = new view('templatefile');
        $view->assign('variablename', 'variable content');
        }
    }
    

    And in your view file :

    <?php echo $variablename; ?>