Creating a PHP website using MVC – 2 Creating the Controller and Template

In the first part of this tutorial series, we looked into how to startup the framework.  The output was displaying the controller and action of a called url. We also found which area is called – the admin or the site area.

In this tutorial, we will look into creating the Controller and Template classes.

For any class we create anywhere, we need to make sure that the filename is ended with ‘.class.php’ because this is how we defined autoloader and a class can be easily identified by just looking into the file system.

In the main index file created in the first part, what we do is create an instance of the controller and call the required method in the controller using call_user_func(). So now we are going to create a Controller class.

Features of a controller will be:

  • Create a Template class
  • Set index function
  • Set other custom functions
  • Set the view page for the template instance
  • Set variables for using inside the view
  • Render the template

In the above steps 1,2,4,5 and 6 are common things among all controllers. Only thing different among controllers are the custom functions. So we can create a base Controller class and implement these features. When we need a custom controller, we extend this base Controller and write only the custom functions.
A base Controller class will look like this. Save the file inside the ‘lib’ folder as Controller.class.php

<?php
/**
 * Base Controller class
 */
class Controller {
 
    protected $template;
    
 function __construct() {
  $this->template = new Template();
 }
    
    function index(){
        error_log("Controller[".get_called_class()."] index method is not defined");
    }
    
    protected function setView($folder,$file){
        $this->template->set($folder,$file);
    }
    protected function setVariable($key,$value){
        $this->template->setVariable($key,$value);
    }
    
    function __destruct(){
        $this->template->render();
    }
}

?>

First we need a template class. A template class will load header, footer and a view page. We assign some variables which are to be used inside the view page into the template page. In the construct method, we create a new instance of the Template class.

Also Read:   Create a Catch the egg game in Godot engine - 5

A controller must have an index method, so we create it here but it will be an error logging method. This index method has to be overridden in the extended controllers. This is just for knowing we didn’t define an index method for a controller.

The setView method sets the folder and filename of the template, so it know where to look for the view file when rendering.

The setVariable method creates a variable to be used inside the view page. It will be more clear after  looking into the Template class.

In the destruct function we render the template so it will be automatically rendered after all processing.

Let’s take a look into the Template class. Save this file inside the ‘lib’ folder as Template.class.php

<?php
/**
 * Template class
 */
class Template {
 
    protected $file;
    protected $folder;
    protected $variables;
    
 function __construct() {
  $this->variables = array();
 }
    
    /**
     * Set the folder and filename for the view template file
     */
    function set($folder,$file){
        $this->folder = $folder;
        $this->file = $file;
    }
    
    /**
     * Set the variables to be exported into the template file
     */
    function setVariable($key,$value){
        $this->variables[$key] = $value;
    }
    
    function render(){
        global $area; //Get the global variable $area
        extract($this->variables); //Extract the variables into the page, so that each key is available inside the page as php variable
        
        //Include defined view
        $filename = ROOT.$area."/view/".$this->folder."/".$this->file.".php";
        if(file_exists($filename)){
            include($filename);
        }
       
    }
}

?>

First we define some variables $file, $folder and $variables.

Also Read:   Godot Engine game tutorial for beginners – Create a 2D Racing Game 2

$file – Filename of the actual view page

$folder – Directoy where the view page is located, so we can have two different views with same name and the file structure is much more understandable.

$variables – The variables to be extracted into the view page. This is an array and the keys are converted into php variables.

In the render method, we just include the previously set template file.

Now we need some functions inside the functions.php file.

<?php

/**
 * Start the head section of the page
 */
function startHeader(){
    $string = "<!DOCTYPE html>\n<html>\n<head>\n";
    echo $string;
}
/**
 * Include a stylesheet from the css folder
 */
function includeStyle($filename){
    global $area;
    $path = "./".$area."/css/".$filename;
    includeExternalStyle($path);
}
/**
 * Include an external stylesheet from another domain
 */
function includeExternalStyle($location){
    $string = "<link rel='stylesheet' type='text/css' href='".$location."' />\n";
    echo $string;
}
/**
 * Inlcude a javascript file from the js folder
 */
function includeScript($filename){
    global $area;
    $path = "./".$area."/js/".$filename;
    includeExternalScript($path);
}
/**
 * Inlcude an external javascript
 */
function includeExternalScript($location){
    $string = "<script type='text/css' src='".$location."'></script>\n";
    echo $string;
}
/**
 * Set title of the page
 */
function setTitle($title){
    echo "<title>".$title."</title>\n";
}
/**
 * End the head section of the page
 */
function endHeader(){
    echo "</head>\n<body>\n";
}
/**
 * Get footer
 */
function getFooter(){
    echo "\n</body>\n</html>";
}


?>

Those are some basic things that you already know.

Now, create a file inside the site/view folder called main.php.

<?php
startHeader();
setTitle('Simple page title');
includeStyle('main.css');
endHeader();
?>
<div id="container">
    <?php echo "This is a sample page - ".$testVar;?>
</div>
<?php
getFooter();
?>

This is how we create pages in this framework. Now create an IndexController by extending the Controller class. Save this file inside /site/controller as IndexController.class.php.

<?php
/**
 * Site Index Controller
 */
class IndexController extends Controller {
 
 function __construct() {
  parent::__construct();
 }
    
    function index(){
        $this->setView('', 'main');
        $this->setVariable('testVar', 'James Bond');
    }
   
}

?>

In the construct function, we just call the super class construct. In the index method, we set the template and set a variable. Now open the website and you can see the output.

Also Read:   Creating a PHP website using MVC - 1

mvcNow what we have is a great flexibility in our view page. We didn’t create a Model class yet and there is not much dependency in any controller class. The view page is so simple that we don’t have to write long head sections including scripts/styles but we can if we want. Basically it is an empty page until we add things into it.

Design the page however we want, but it will be powered by our wonderful mvc framework.

In the next part, we create Model classes and integrate with MySQL.

Never miss any content from Codetuto!

Subscribe to Codetuto Newsletter and be the first to recieve our latest posts and tutorials

Subscribe Now For Free

[Total: 0    Average: 0/5]