Pranav
Pranav

Reputation: 2172

php custom mvc framework | Load a view file as a string

I want to implement functionality like CodeIgniter does in its loadview function - While loading the view we pass third parameter "true" so that the page will be taken as a string.

Using file_get_contents() is correct option while wrting custom mvc framework ?

I hav a function to load view as -

function loadView($directoryPath, $page, $data = array()) {

        extract($data);
        // construct path for loading the view
        $viewURL = $GLOBALS['config']['dir-views'];
        $path = $viewURL . DS . $directoryPath . DS . $page;

        // actual loading of a view.  
        include $path;
    }

Upvotes: 0

Views: 729

Answers (1)

Vadim Ashikhman
Vadim Ashikhman

Reputation: 10136

It depends on your goals. If you want to get the raw view data then use file_get_contents(). If a view contains any php code that needs to be executed use ob_start and include.

Ob_start example:

function loadView($directoryPath, $page, $data = array()) {

    extract($data);
    // construct path for loading the view
    $viewURL = $GLOBALS['config']['dir-views'];
    $path = $viewURL . DS . $directoryPath . DS . $page;

    // actual loading of a view.  
    ob_start(); // Turn on output buffering
    include $path; // Output the result to the buffer
    return ob_get_clean(); // Get current buffer contents and delete current output buffer
}

ob_end_clean()

Upvotes: 2

Related Questions