Search code examples
phptemplatesoutput-buffering

Using output buffering as a template-engine


So I'm writing my MVC and need to display my views.

It's pretty simple at the moment, just wrapped in a function inside my main controller.

ob_start();
require_once('views/' . $fileName . '.php');
$output = ob_get_contents();
ob_end_flush();
return $output;

However, I don't quite understand how to set all the variables within the view I am rendering, and this is the most important part (no shit).

Any tips in regards to doing this? And any code samples you want to share in regards to a basic MVC framework?

I'm writing the most basic thing I could think of, with just a few controllers, models, views, an autoloader, and a index.php to route all the requests. I'm not interested in rewriting using IIS rewrite module, so I'm just running _GET to fetch the query string.

Thanks in advance, you people are always a great help.


Solution

  • This is a rough idea (code taken and modified from one of my own frameworks, I built a long ago, only to clarify my understanding), you may create a View class and put this function as method, but this function could be used as

    $content = render('view_name', array('name' => 'Heera', 'age' => '101'));
    

    Function render() :

    function render( $filename, $data = array() )
    {
        extract($data, EXTR_SKIP);
        ob_start();
        include "views/$filename.php";
        return ob_get_clean();
    }
    

    You can think of a view like this

    <div><?= htmlspecialchars($name) ?></div>
    <div><?= htmlspecialchars($age) ?></div>
    

    You can follow some existing frameworks to (I did when I developed this one and helped me a lot) and write your own.