Question

I trying to write my own MVC (Please don't suggest me any existing mvc I want to make my own) and now to render a page I do this:

Header:

<!DOCTYPE html>
<head>
<!-- Some contents -->
</head>
<body>

Footer:

</body>
</html>

Index function of a controller:

public function index(){
    $this->view->render('header');
    $this->view->render('index');
    $this->view->render('footer');
}

Render function:

public function render($file){
    require "views/$file.php";
}

Instead of doing that how I can do something like this?

Layout:

<!DOCTYPE html>
<head>
<!-- Some contents -->
</head>
<body>
<?= $page //$page will be replaced with index.php content ?>
</body>
</html>

Index function of a controller:

public function index(){
    $this->view->render('layout', 'index');
}
Was it helpful?

Solution

You can have a render function like:

function render ($template, array $environment = array()) {
    extract($environment);
    ob_start();
    include $template;
    $contents = ob_get_clean();
    return $content;
}

The extract() function will import all variables from the array into the current scope making them available to your template.

http://nl1.php.net/manual/en/function.extract.php

ob_start() will buffer all content from that point onwards.
ob_get_clean() will get the contents of the buffer end ends the buffering of output.

http://nl1.php.net/manual/en/function.ob-start.php

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top