What is the best way of including a view file in a controller

Howdy, I’m writing a very simple little PHP script to manage messages via a front-end form.

I’ve written a “controller” file which checks the source of the request GET|POST and decides how to proceed based on that.

If there is a POST, I validate the form that its my form, validate the form itself, filter values etc and finally prepare variables to be passed back to the “view”.

At the moment, I’m using this technique:

class View
    protected $_vars = array();

    public function set($name, $value)
        $this->_vars[$name] = $value;

    public function render($view)
        $file = sprintf('%s.php', $view);

        if (!file_exists($file) && !is_readable($file)) {
            return false;

        if (is_array($this->_vars) && !empty($this->_vars)) {

        require_once $file;

$view = new View;
$view->set('greeting', 'Hello World');

I’ve looked at other frameworks like Zend to see how they do it, I think they use some kind of stream context technique that I’ve never seen before.

I dont need all the bulk of a framework for my little script but I would like to build it as best I can. So I was wondering if anyone could suggest a good technique to include view files, I would also like to give my view access to $this if possible.


Welcome to Sitepoint Tyler.

I posted a very simple Template object in this post a little while back which may help out some.

Oh nice, that does help a lot actually, how come ya’ll are using output buffering? Is there anyway to give the view/template file access to the View/Template class?

The output buffering is a common technique used so that you can essentially nest views within views. Where is becomes important is when you separate out the layout and main content. In that case you would want to render the layout (wrapper) and embed the main content. There are other uses, but primarily that and sending output to the browser all at the same time, so that headers and all application logic is nestable.

The tpl file have access to $this since they are being executed within a method inside the object.