I starting to learn about OOP PHP and have made a class. It simply replace tags in a template file with content.
<?php
class templates
{
var $file='tem.tpl';
var $tags;
var $content;
function loadfile()
{
if(!$open=@file_get_contents($this->file))
{
echo "$this->file could not be opened";
exit;
}
return $this->replacetags($open);
}
function replacetags($open)
{
$tagstoreplace=str_replace($this->tags,$this->content,$open);
return $tagstoreplace;
}
}
?>
As this is one of my first attempts at OOP I’m just wondering whether I’m on the right tracks.
I’m guessing though that a procedural script would perform this task just as well.
Good luck with it, but learning how to use OOP effectively is really quite a journey.
The acid test will be how many of the classes you develop for your blog will you be able to use in other projects, if you have this in the back of your mind as you write you will get there eventually.
What happens if you have another template, ‘tpl2.php’?
You could inject that value into your class meaning you could use it in several different websites or applications.
Also imagine how you’d like to write this class, so that you can remember what it does, it should sound like a short phrase.
$t = new templater ( 'tpl3.php' );
echo $t->output();
Meaning you have to have a constructor which sets the variable for which template to use. e.g.
class templater {
private $template;
function __construct( $tempate_name){
$this->template = $template_name ;
}
...
function output(){
return $data ; //the string of html or whatever
}
}
Leave it up to your runtime code to decide what to do with the stream of data, maybe its only a html snippet that needs to be output further down the PHP page, maybe you want to do some more processing on it. The more options you leave open for yourself the more places you can include and use this class.
There are lots of principles here that I have only touched on, you really need to find a good book to read up on this to get the full benefit.
ps if you are trying out OOP, then please, please use PHP5, the syntax you have used is for PHP4
FYI, you shouldn’t use str_replace for templating, but strtr
Consider the simple template (from the strtr doc page) : “hi all, I said hello”
$str = "hi all, I said hello";
echo str_replace(array('hi', 'hello'), array('hello', 'hi'), $str); // echoes "hi all, I said hi", because first 'hi' is replaced with 'hello' and then both instances of 'hello' are replaced with 'hi'
echo strtr($str, array('hi'=>'hello','hello'=>'hi')); // echoes "hello all, I said hi"
It’s good to see that I’m sort of on the right tracks with this.
It’s pretty open and it doesn’t really matter the format of the data that you want to use. It will work with any number of tags and pieces of data to replace the tags with.
The reason I am trying to make this is because I am making a simple blog and am trying to keep the code as clean as possible.