Welcome!

Join our community of MMO enthusiasts and game developers! By registering, you'll gain access to discussions on the latest developments in MMO server files and collaborate with like-minded individuals. Join us today and unlock the potential of MMO server development!

Join Today!

[Tutorial][PHP] Simplest templating system

Newbie Spellweaver
Joined
Dec 6, 2011
Messages
11
Reaction score
8
Hello RageZone. As this is one of my firsts posts, I thought that I will start off something that may be useful before I start to ask :)

1. Create a file named template.class.php (it does not really matter, it just need to be required/included into a document)

2. Put into a file:

PHP:
<?php
class template{
    private $template_root = 'templates'; // This is the folder where we keep templates

    private $template; // This is our template content if we need to return a template into a string or something, instead of echo it

    private $template_extension = 'html'; // This is the extension that we are going to use to grab our templates from root

    private $pattern = '{c}'; // c is our variable that we will replace it on template assemble

    function __construct($filename, $data = array(), $echo_method = false){
        $file = $this->template_root.'/'.$filename.'.'.$this->template_extension; // Assign a local variable to initialize the PATH of a file
        if(file_exists($file)){ // We checking up if a file exists
            $content = file_get_contents($file); // On existence, we grabbing the content from a file, and returning it into a local variable
            if(!empty($data) && is_array($data)){ // If $data is not an empty, so we can loop it at least once, and if is an array, to avoid the error message
                foreach($data as $variable => $value){
                    $content = str_replace(str_replace('c', $variable, $this->pattern), $value, $content); // We looping up a whole $data array with given variable patterned name in a html file, and handles a str_replace of that patterned variable to be replaced with value
                }
            }

            if($echo_method) // If we decided to use a echo method, so we need to set a boolean to true
                echo $content;
            else $this->template = $content; // If we not, the private variable of a class scope getting value of looped template, to can be passed then as a return to a function below. This is because a constructors in PHP cannot return any values
        }else{
            // You can handle here a exception for not existing template, I chosen to die with an message on missing template, and stop executing the code further
            die('You are missing a template file in: '.$file);
        }
    }

    public final function get(){
        return $this->template;
    }
}

Then require a file into your document, so you can use it later

3. Usage: Method 1
To use the method you have 2 choices.

Return the template to a variable:
PHP:
    $template = new template( file*, data*, method* );
    $my_template_variable = $template->get();

OR

Echo the template anywhere you want, just do:
PHP:
    new template( file* , data*, true);

4. Usage: Method 2
We can simplify our lives, and do not deal with classes at all, then just define a function called template, under the definition of class in our template.class.php:
PHP:
function template($filename, $data = array(), $echo_method = false){
    $template = new template($filename, $data, $echo_method);
    if(!$echo_method)
        return $template->get();
    else return null;
    new template($filename, $data, $echo_method);
}
And then use it in same two ways as:

PHP:
    $my_template_variable = template(file*, data*); // We don't need a method here, because false is our default, in the class and in the function, so we are safe and sure that won't happen dumb any error.

OR

PHP:
    template(file*, data*, true);

5. Summary and example
We have used basics of PHP language, and only. We managed to understand here a little bit of class, and their behaviours.

The way it can be worked with is simply create a index.html in templates folder.
Put content of:

Code:
Hello my name is: {name}

Then create a index.php and fill that in with:
PHP:
template('index', array("name"=>"John Smith"), true);

and thats should get it working then.
 

Attachments

You must be registered for see attachments list
Last edited:
Newbie Spellweaver
Joined
Dec 6, 2011
Messages
11
Reaction score
8
Thanks :) More on the way... just need to do College stuff before I can have more time to write something more advanced, like session database handler, and also trying to find appropriate examples to lift the upcoming tutorials:p
 
Elite Diviner
Joined
Jul 12, 2007
Messages
417
Reaction score
24
Take a look at HMVC and combine it with a framework like Laravel or Codeigniter :p (yes I know Codeigniter is outdated but it's still a nice framework)
 
Experienced Elementalist
Joined
Dec 17, 2008
Messages
209
Reaction score
31
Re: Trash

I'm sorry but this is a highly inefficient piece of code that I wouldn't even recommend my competition to use. You seem to have a somewhat basic understanding of working with classes yet you fail to utilize them properly. And like שเ๒єtгเ๒є just said, using echo or print in a class constructor is bad bad programming and shame on you for doing it. Who taught you?

Here, let me just quick-paste something I wrote a couple weeks ago that'll suit peoples needs far more than whatever you call this thing.
PHP:
<?php

class template {

	private $source = "";
	private $vars = array();
	
	public function __construct($source = "") {
		if(substr($source, 0, 1) == "@") $source = file_get_contents(substr($source, 1));
		$this->source = $source;
	}
	
	public function __isset($var) { return isset($this->vars[$var]); }
	public function __get($var) { return (isset($this->vars[$var])) ? $this->vars[$var] : false; }
	public function __set($var, $val) { $this->vars[$var] = $val; }
	
	public function __toString() {
		$output = $this->source;
		foreach($this->vars as $var => $val) {
			if(substr($val, 0, 1) == "@") $val = file_get_contents(substr($val, 1));
			$output = str_ireplace("%[".$var."]%", $val, $output);
		}
		return $output;
	}

}

?>

Anyone with moderate understanding of PHP should be able to put this to use, and if not then let me write up an example for you.

use class:
PHP:
<?php

include "class.template.php";

$tpl = new template("<html></html>"); // either type in a template from scratch
$tpl = new template("@path/to/template"); // or use the @ and then put a path to import a file
$tpl->variable = value; // modify variables inside the template accordingly
$tpl->variable = "@path/to/file"; // you can use the import thing here too
print $tpl; // then print out the template after import and variable modifications

?>
example template file:
Code:
<html>
<head>
<!-- this is a defined variable, it can be replaced when properly used in a code -->
<title>%[title]%</title>
</head>
<body>
%[body]%
</body>
</html>

Enjoy.
 
• ♠️​ ♦️ ♣️ ​♥️ •
Joined
Mar 25, 2012
Messages
909
Reaction score
464
Re: Trash

I'm sorry but this is a highly inefficient piece of code that I wouldn't even recommend my competition to use. You seem to have a somewhat basic understanding of working with classes yet you fail to utilize them properly. And like שเ๒єtгเ๒є just said, using echo or print in a class constructor is bad bad programming and shame on you for doing it. Who taught you?

Here, let me just quick-paste something I wrote a couple weeks ago that'll suit peoples needs far more than whatever you call this thing.
PHP:
<?php

class template {

	private $source = "";
	private $vars = array();
	
	public function __construct($source = "") {
		if(substr($source, 0, 1) == "@") $source = file_get_contents(substr($source, 1));
		$this->source = $source;
	}
	
	public function __isset($var) { return isset($this->vars[$var]); }
	public function __get($var) { return (isset($this->vars[$var])) ? $this->vars[$var] : false; }
	public function __set($var, $val) { $this->vars[$var] = $val; }
	
	public function __toString() {
		$output = $this->source;
		foreach($this->vars as $var => $val) {
			if(substr($val, 0, 1) == "@") $val = file_get_contents(substr($val, 1));
			$output = str_ireplace("%[".$var."]%", $val, $output);
		}
		return $output;
	}

}

?>

Anyone with moderate understanding of PHP should be able to put this to use, and if not then let me write up an example for you.

use class:
PHP:
<?php

include "class.template.php";

$tpl = new template("<html></html>"); // either type in a template from scratch
$tpl = new template("@path/to/template"); // or use the @ and then put a path to import a file
$tpl->variable = value; // modify variables inside the template accordingly
$tpl->variable = "@path/to/file"; // you can use the import thing here too
print $tpl; // then print out the template after import and variable modifications

?>
example template file:
Code:
<html>
<head>
<!-- this is a defined variable, it can be replaced when properly used in a code -->
<title>%[title]%</title>
</head>
<body>
%[body]%
</body>
</html>

Enjoy.

As .NET developer this is one of the few things that really inpresses me, because I define PHP being worse, usually, because people use it worse, usually. I did not know PHP allows to override such a ToString method to simply be able to print out anything (of the class) when printing the instance. This is a very good code snippet I would do almost similar in .NET.

Just one last thing. You should rather put a boolean variable on the constructor call that defines this is raw template html or a path to raw template html file instead of simply checking this up by the first sign (@), because the thing with the first char is not well designed because you still have to explain how to use it, even when the user knows the signature of the class and its members.

However, still well done. =)
 
Experienced Elementalist
Joined
Dec 17, 2008
Messages
209
Reaction score
31
Re: Trash

As .NET developer this is one of the few things that really inpresses me, because I define PHP being worse, usually, because people use it worse, usually. I did not know PHP allows to override such a ToString method to simply be able to print out anything (of the class) when printing the instance. This is a very good code snippet I would do almost similar in .NET.

Just one last thing. You should rather put a boolean variable on the constructor call that defines this is raw template html or a path to raw template html file instead of simply checking this up by the first sign (@), because the thing with the first char is not well designed because you still have to explain how to use it, even when the user knows the signature of the class and its members.

However, still well done. =)

You make a good point. I only use the @ character because.. well.. my OCD kinda acts up when it comes to an overflow with booleans at the end of functions. Still, this is only a basic code that could, and should, be improved upon further.
 
Back
Top