Template System – Complete Tutorial – The labour Part!
So, now you have seen my babe here and you might be thinking what is this all about. Let me begin by telling you, all in all, this is a simple template class compared to the big giants like smarty. But even then, this class has been a boon to me and my team. I have developed and improved it over a few months. Though not perfected it yet, but I plan to spend a while to improve it. Okay I guess I have missed on why we are here spending hours orin fact days together to develop a template system. Well read my post on Web Application Development. If you read this topic, it is apparent that there are 3 layers of a web application.
- The data layer,
- the processing layer( can be further divided) and
- the presentation layer.
For most of the conventional applications, the Layer 1 and 2 are managed by the same people. More often than not, we find people who are good in the processing layer, dealing with PHP are bad in CSS, or the presentation layer. So, this template is an effort to make these layers separate. We have had a lot of trouble doing the same, but nevertheless, its beenachived. Okay so how does this work is the main question…
Lets put down the logical steps on the running of this template:
- Load the file with the template
- Check for the for statements
- Check for the if statements
- Check for variables in the template
- Check for included templates, and process them also.
Whoa! Some programming is going to be needed for that! So, let’s go ahead and do what is required. I would like to get to your notice that I am still getting in line with the PEAR coding standards, so you might consider me a bit immature as of now
. But well anyhow, the writing style is pretty clear to view the stuff. The program is what is more important here. Okay so moving ahead, the first part of the function,
function template($template_file,$template_vars= array(),$template_path=”")
{
$this->contents = $this->getTemplate($template_file,$template_path);
$this->template_vars = $template_vars;
$this->template_path = $template_path;
}
function getTemplate($template_file,$template_path = “”)
{
$txt = substr($template_path,strlen($template_path) – 1,1);
if(($txt != “/”) && ($txt != “\\”) && ($txt != “”))
{
$template_path = $template_path.”/”;
}
if(function_exists(”file_get_contents”))
{
// PHP 5 Method!
$full_path = $template_path.$template_file;
$contents = @file_get_contents($full_path);
}
else
{
// The traditional method
$f = fopen($template_file,”r”);
$contents = fread($f,filesize($template_file));
}
return $contents;
}
now when you use the template like
$tpl = new template(”template.html”,$tpl_vars,”e:/www/”);
It will firstly open load the template function, which will then go to the getTemplate method which will then check if its PHP 4 or 5 (though PHP 4 is history now), open the file and get the contetns of the file in a variable. It then passes back these contents to the main function, which stores the contents in a class level variable namely $contents. Now the story moves ahead. These are the next few set of functions.
function put($find, $replace)
{
$this->template_vars[$find] = $replace;
}
function process_template($contents)
{
$contents = $this->filter_fors($contents);
$contents = $this->filter_ifs($contents);
error_reporting(0);
$contents = $this->filter_php_funcs($contents);
$contents = $this->process_var_replace($contents);
$contents = $this->replace_var_array($this->template_vars,”,$contents);
$contents = $this->process_includes($contents);
$contents = $this->check4vars($contents);
return $contents;
}
function render($do_as_string = false)
{
$this->contents = $this->process_template($this->contents);
if($do_as_string == false)
{
echo $this->contents; // PRINTS THE ENTIRE CONTENT
}
else
{
return $this->contents; // RETURNS THE CONTENT AS A STRING
}
error_reporting(1);
}
The function put is added to declare the template variables, after the initiation of the template. So if you, in later stages want to change the value of the template variable, you can use the this function.
The next function is process_template. Okay, I have been a bit foolish while naming these functions, but nevertheless, they do the job. This function actually processes the template. It filters almost every thing from the contents and makes it ready for the display. It runs all the functions one by one and thus processes the template.
“render” does what it says. It renders the tempalte. Many a times, you would want the render as string or as an echo. If you pass false into it i.e.
$content = $tpl->render(false);
echo $content;
This will be helpful when you want to replace certain contents manually. But anyhow, you can decide if you want to get it as variable or directly let the template class echo it. Now lets move to more details. The next set of fuctions is relating to replacement of variables. This mainly does the work of replacing the vairables used in the template with the ones we are going to set up in the php file. let me get the code across to you now
function check4vars($contents)
{
while(strpos($contents,’{$’,$end) > 0)
{
$start = strpos($contents,’{$’);
$end = strpos($contents,”}”,$start);
$txt = str_replace(’{$’,”",substr($contents,$start,($end – $start)));
$contents = str_replace(’{$’.$txt.”}”,$this->template_vars[$txt],$contents);
}
return $contents;
}
function replace_var($var,$val,$content)
{
return str_replace(”{”.$var.”}”,$val,$content);
}
function process_var_replace($contents)
{
foreach($this->template_vars as $key=>$val)
{
$contents = str_replace(’{$’.$key.’}',$val,$contents);
}
return $contents;
}
function replace_var_array($var_name, $var_key,$content,$is_first = true)
{
if(!is_array($var_name))
{
return $content;
}
foreach($var_name as $key=>$val)
{
if(is_array($val))
{
$key = ($var_key == “”) ? “$”.$key : “[".$key."]“;
$content = $this->replace_var_array($val,$var_key.$key,$content,false);
}
else
{
if(($val != “”) && ($var_key == “”))
{
$content = $this->replace_var($key,$val,$content);
}
else
{
$content = $this->replace_var($var_key.’['.$key.']‘,$val,$content);
}
}
}
return $content;
}
These are very simple functions. What it does is replaces variables one way or another! So every variable written as {$xx} is replaced with its value is $tpl->template_vars[xx]. This is a simple logic and should be pretty easy to digest for you guys. Let us begin with replace_var. This function takes up the keys and replaces them with the values. Again a simple replacer function, as the name suggests. The fuction process_var_replace was written in the very initial stages of the making of this system. How the system originally worked was, it would iterate through all the variables in the template_vars array, and replace the {$key} with the {$val}, i.e. the array keys found in the content with the values. This was a very good idea to begin with, and I was proud of myself, but later on when I was writing the system in more depth, did I find out how wrong I was! I had got it all wrong. And now, I had to correct my mistakes. Anyhow I did decide to keep it as such as it was a very simple iteration, and wasnt eating up much of memory. Just gave me an extra bit of security (against programming lapses, if I had one
).
The next function is “replace_var_array“, which actually replaces an entire array in the string. This uses the function replace_var to actually replace the variable, and calls itslef, to make sure that all the values are replaced one by one. Again this functions much in the same was the the previous function did. Though, in later stages of development I wasnt too very convinced by the existance and use of this function, I chose to keep it as such. It does help me in other places. Though it doesn’t have much role after the next function I am going to describe, somehow, I really dont feel it is a very good idea to disturb the exisatace of this function. I hope I dont sound superstitious, but I am a bit wary about what I delete. When we actually make a public release of the class, we can consider on keeping or removing these fuctions. But for now I am keeping them in there!.
Now let us move to the first function of the previous set. It is “check4vars“. What this function does is, it checks the content string if there are any variables unreplaced, such as {$aasdf} which might not be there in the array, but keeping it as such can look bad. So, what do we do, we create this function. It checks all the variables and replaces them with the values. If there are no values given, it just replaces it with a null value (a little bit like PHP, who considers undefined variables as NULL values). Afterall, I am a PHP fan, and following PHP is something that fascinates me. I think I should pause here, take a breath and come in with more details on the tutorial in the next “post”? What do you suggest? I wanted to make this entire thing as a single post, but I guess it is just too long. In the next post, I am going to introduce to the “brains” of this engine. These brains, they actually let you define some logics in the template and let you use control statements, like ifs and fors. Hope this has been an interesting read thus far. See you as soon as possible!
???????? ??????, ???????!??? ???????? ??????????? ??????????, ?? ???? ??????? ? ???? ??????????? – ??? ??????? ?? ??????. ????? ??????, ????? ?????????????? ?????? ??????? ????????????????, ??? ?????????? ?? ?????? ?????? ? ??????? ??????????? ???????.
?????? ???? ????? ??????????? ????? ??????????? ?????. ???? ?????? ? ???? ????? ? ??????????? ??????? ????????????? ???????. ??? ? ????? ????????? ???????????? ????? ?????, ? ?????? ??????? ????????? ????? (??? ?????? ???????? ?????, ?.?. ?? ????????? ? ???????). ???????? ??????, ?????????, ??????? ??????? ????????? ? ????? ???? ??????? ?????????? – ??? ??????? ??????????.