Basic PHP Templates Class


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <?php
  2. class Template{
  3. private $dir;
  4. private $data = array();
  5.  
  6. public function __construct($dir) {
  7. if( is_dir($dir) ) {
  8. $this->dir = $dir;
  9. } else {
  10. throw PHPTemplateException('Directory does not exists');
  11. }
  12. }
  13.  
  14. public function assign($variable, $data) {
  15. $this->data[$variable] = $data;
  16. }
  17.  
  18. public function display($template) {
  19. $template = rtrim($template, '.php') . '.php';
  20. if( file_exists($this->dir . $template) ) {
  21.  
  22. $this->__fetch($this->dir . $template);
  23.  
  24. return;
  25. }
  26.  
  27. throw PHPTemplateException('File does not exists');
  28. }
  29.  
  30. private function __fetch($____FILE) {
  31. extract( $this->data );
  32. include( $____FILE );
  33. }
  34. }
  35.  
  36. class PHPTemplateException extends Exception {
  37. public function __construct($message) {
  38. parent::__construct('[PHP Template]:' . $message);
  39. }
  40. }

URL: http://www.talkphp.com/general/4844-php-template.html

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.