RenderView Method for a Custom MVC Framework

The renderView method will receive a view file and substitute variable values into it. This is done in a clever way. As you know, the variables used in the view file are contained in the data property of the Page class object.

These variables are an associative array. We need to convert this array into real variables, and then include the view file via include. In this case, the variables available in this file will receive their values and the output will be pure HTML code with the variable values already substituted.

To convert the array into variables, we use the special function extract:

/core/View.php<?php
  private function renderView(Page $page) {
    $viewPath = $_SERVER['DOCUMENT_ROOT'] . "/project/views/{$page->view}.php";
    
    if (file_exists($viewPath)) {
      ob_start();
        $data = $page->data;
        extract($data);    // convert array to variables
        include $viewPath; // include the view file
      return ob_get_clean();
    }
  }
?>