Thread: PHP Template
View Single Post
Old 08-12-2009, 11:37 AM   #1 (permalink)
Sirupsen
The Contributor
 
Sirupsen's Avatar
 
Join Date: May 2009
Posts: 53
Thanks: 2
Sirupsen is on a distinguished road
Bricks PHP Template

Greetings! I am currently making a few projects, but I am very worried about how I should do my templating system so I do not at some point regret how I did it, and want to recode it!

Basically, I just want to insert informations into my sites easily but also, it shouldn't become a mess with shit loads of php calls inside the HTML. I could pretty easily do something like this:

PHP Code:
<?php $articles $object->fetchArticles(); ?>
<?php 
foreach ($articles as $article) : ?>
    <h1><?php echo $article['title']; ?></h1>
    <p><?php echo $article['content']; ?></p>
<?php endforeach; ?>
That'd basically just require the fetchArticles method to return an array, containing an array for each article:

Example:
PHP Code:
public function fetchArticles() {
   
$query connectToDbAndRetrieveInformation();

   while (
$row mysql_fetch_array($query)) {
      
$data[] = array(
         
'title' => $row['title'],
         
'content' => $row['content']
         
// And for more fancy stuff something like this:
         
'time' => $this->timeDifference($row['time']),
         
'author' => $this->authorName($row['author_id'])
      );
   }
   
   return 
$data;

However, this probably is a pretty bad way to do it (I think?), I don't want to use something big as Smarty and have a whole different weird markup (the foreach loops in smarty are just weird) for the foreach loops. (And it's slooow.. And I won't need half the features) I have made some pretty simple stuff involving replacing {something} with a variable set. However, I can't use PHP in the template file (like if I needed to check something before printing something out, like if the user is administrator). Here is what I have currently:

PHP Code:
<?php
class Template {
    private 
$path 'template/';
    private 
$values = array();

    private function 
__set($name$value) {
        
$this->values[$name] = $value;
    }

    public function 
display($file) {
        
$file $this->path $file;
    
        
$file_content file_get_contents($file);
            
        foreach (
$this->values as $key => $value) {
            
$file_content str_replace('{' $key'}'$value$file_content);
        }    

        echo 
$file_content;
      }
}
?>
Maybe this could be expanded to be useful?

I hope I can get some help on doing this part properly. :)
Send a message via AIM to Sirupsen Send a message via MSN to Sirupsen Send a message via Yahoo to Sirupsen Send a message via Skype™ to Sirupsen
Sirupsen is offline  
Reply With Quote