JasonDavis
JasonDavis

Reputation: 48933

ob_start() Alternative for templates in PHP?

Question Updated

I am building an MVC framework, for my templates and views, I will have a main page template file and my views will be included into this template.

The only way I have seen to do this is to use output buffereing

ob_start();
include 'userProfile.php';
$content = ob_get_clean();

Is there any other way of doing this? I think output buffering is not the best on performance as it uses a lot of memory

Here is a sample controller, the $this->view->load('userProfile', $profileData); is the part that will be loaded using output biffering so that it can be included into the main template below into the $content part

view class

public function load($view,$data = null) {

    if($data) {
        $this->data = $data;
        extract($data);
    } elseif($this->data != null) {
            extract($this->data);
    }

    ob_start();
    require(APP_PATH . "Views/$view.php");
    $content = ob_get_clean();
}

controller

/**
 * Example Controller
 */
class User_Controller extends Core_Controller {



    // domain.com/user/id-53463463
    function profile($userId)
    {
        // load a Model
        $this->loadModel('profile');  
        //GET data from a Model
        $profileData = $this->profile_model->getProfile($userId);

        // load view file
        $this->view->load('userProfile', $profileData);
    }
}

main site template

<html>
<head>

</head>

<body>

<?php echo $content; ?>

</body>
</html>

Upvotes: 2

Views: 5672

Answers (1)

Jon
Jon

Reputation: 437336

Using a template system is not necessarily tied to output buffering. There are a couple of things in the example code you give that should certainly not be taken for granted:

One:

flushblocks(); // what does this do??

And two:

$s = ob_get_clean();

Why does the code capture the template output into a variable? Is it necessary to do some processing on this before outputting it? If not, you could simply lose the output buffering calls and let the output be sent to the browser immediately.

Upvotes: 0

Related Questions