7

This tutorial is intended for people who are looking for alternative to PHP template engines like smarty, twig, dwoo, TBS, and others. Not all developers are willing to take the extra efforts needed to learn the template engine syntax. Some are just left behind thinking that PHP is a template engine itself and there is no need for another template engine.

Regardless of what you think about PHP, it has been proven that PHP can be written in procedural, OOP, CLI interface, and spaghetti style .In this particular tutorial, I will be demonstrating how to use PHP effectively as a template engine by way of business logic and presentation logic separation.

What are the requirements?
1. Basic knowledge of OOP ( we are not going to write one, but I will give you one to use. This is for one file only).
2. Xampp or equivalent
3. Basic knowledge with MySQL and PDO.

Objectives
1. The main objective of this tutorial is to minimize the presence of the application's business logic inside the presentation logic.
2. Introduction to PHP magic function called __toString().
3. Avoiding the while loop after the MySQL query, but instead passing the result as an array.
4. Simple exposure to PDO

What is business logic?
Business logic can be the function processing a resulting array from another function, mySQL queries, evaluated results from statments to trigger another function, and all other things that are working behind the background.

What is Presentation logic?
Presentation logic is mainly the html tags and the output of a function or a class. Meaning all outputs from PHP function and classes that are considered as final product.

Example:

function say_something($string){
    return $string;
}

The output $string can be considered to be a presentation logic only if no other functions or methods are going to evaluate this output.

so, in doing like this

echo say_something('hello world');

makes that output as part of the presentation logic. However, if we do this

function evaluate_string($new_string){

    return $new_string;

}

echo evaluate_string(say_something('hello_world');

the function evaluate_string() holds the final responsiblity in delevering the output as part of the presentation logic and not the say_something() function.

What is Spaghetti codes?

Spaghetti codes are codes written in PHP with both the business logic and presentation logic mixed on a single page.

For example, let us examine codes below. Note This is an example only, it is highly recommended to use PDO or MySQLI.

<?php

## establish a mysql connection => business logic
mysql_connect("localhost", "db_user", "db_password") or die(mysql_error());

mysql_select_db("db_name") or die(mysql_error());

## select query for the your_table table => business logic
$result = mysql_query("SELECT * FROM your_table") 
or die(mysql_error());  

## all echoed items below are presentation logic
echo "<table border='1'>";
echo "<tr> <th>Name</th> <th>Age</th> </tr>";

## while loop is a business logic, because of the mysql_fetch_array function.
while($row = mysql_fetch_array( $result )) {
    ## all these are presentation logic
    echo "<tr><td>"; 
    echo $row['one'];
    echo "</td><td>"; 
    echo $row['two'];
    echo "</td></tr>"; 
} 

echo "</table>";

The source code above is pretty cluttered and mixed up. It lacks organization and it will be hard to maintain later on.

In this tutorial, I will show you how to organize your codes into maintainable codes. Something that can protect your source from accidental deletion.

Step One
Open your favorite source code editor e.g. notepad++. Copy and paste codes below save as template.php.

Filename: template.php

<?php

    class Template{

        public function __construct(){}


        public function __toString(){

        return self::data($data=array());

        }

        public function data($data = array()){

            return $data;

        }

    }

        $view = new Template();

Do the same with the codes below save as simple_pdo.php

filename: simple_pdo.php

<?php

    $dbsn = 'mysql:host=localhost;dbname=your_dabasename';
    $username = 'db_user';
    $password = 'db_password';
    try {

        $db_con = new PDO($dbsn, $username, $password);
        $db_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

       } catch (PDOException $e) {

        echo $e->getMessage();
    }


    function get_items($db_con,$query){

        if($db_con){
            try{
            $db= $db_con->prepare($query);
            $db->execute();
            $row_count = $db->rowCount();
            $result = $db->fetchAll();
            return array($result,$row_count);

        }

        catch(PDOException $e) {
                    return false;
                }
        }
        else{
            return false;
        }
    }

create the index.php

<?php

    require_once('template.php');
    require_once('simple_pdo.php');

    ## lets test the template class
    $fruits = $view->data(array('apple','banana','orange','grapes','pears'));

    ## without using the template class
    $title = 'Fruits'; 

    include_once('index.tpl');

create the template file.
Filename: index.tpl

<!DOCTYPE html>
<html>
<head>
<body>

    <p> title : <?php echo $title ;?></p>

    <ul>

    <?php 
    foreach ($fruits as $item){
    ?>

        <li><?php echo $item; ?></li>

    <?php
    }
    ?>

    </ul>

  </body>
  </html>    

step two
direct your browser to index.php to view the result.

How to use the above script to show database result?
To display the results from a database query, we can easily do this on the index.php

$query = ('SELECT id,title FROM `table` );
$data = $view->data(get_items($db_con,$query)[0]);

remember the $db_con is a persistent db connection..

We can do this on the template file

<?php foreach($data as $v){?>

        <?php echo $v['id'];?> : <?php echo $v['title'];?> <br/>

<?php } ?>

That's pretty much it. Practice the same techniques used in this tutorial on your next project..

Thanks,

Veedeoo

Edited by Dani: Converted to tutorial

Votes + Comments
great
3
Contributors
3
Replies
56
Views
3 Years
Discussion Span
Last Post by Gideon_1
2

Just to let you know, I am planning to add a compile function to the Template class later.
Although I am trying to not go very far from PHP doing the template rendering, I want to make sure that the class will be capable of something like this.

business

$fruits = $view->data(array('apple','banana','orange','grapes','pears'));

presentation

<ul>

{foreach $fruits as $item}
    <li>{$item}</li>
{/foreach}

</ul>

Though it may appear to be like smarty, the truth is it is not. I will be using simple PHP function to compile the content of the index.tpl file.

Please stand by for that modification of the class Template.

Edited by veedeoo: info added.

1

Well done veedeoo! Let's hope after reading this, people atleast realize how easy it is to implement PDO and stop using mysql_*. Everytime I see a question like "how do I make my code more secure" and see them using mysql_*, I die a little inside. Lol

Edited by DJBirdi

Votes + Comments
thanks :)
0

Thumbs up, very very awesome, you just pin pointed my most hated thing in PHP, spaghetti codes.

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.