view.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. class View {
  3. // Path to templates dir
  4. private $path = 'templates';
  5. // Name of template, default: default
  6. private $template = 'default';
  7. // Stores variables for templates
  8. private $_ = array();
  9. /**
  10. * Assign a key/val pair for the template
  11. *
  12. * @param String $key Key
  13. * @param String $value Variable
  14. */
  15. public function assign($key, $value) {
  16. $this->_[$key] = $value;
  17. }
  18. /**
  19. * Sets templates name
  20. *
  21. * @param String $template Name of template
  22. */
  23. public function setTemplate($template = 'default') {
  24. $this->template = $template;
  25. }
  26. /**
  27. * Load template and return result
  28. *
  29. * @return string Output of template
  30. */
  31. public function loadTemplate() {
  32. $tpl = $this->template;
  33. $file = $this->path . DIRECTORY_SEPARATOR . $tpl . '.php';
  34. if(file_exists($file)) {
  35. // Write output to buffer
  36. ob_start();
  37. extract($this->_); // make vars available via name not array, forbidden vars: $tpl, $file, $output
  38. // Include template and save output to $output
  39. include($file);
  40. $output = ob_get_contents();
  41. ob_end_clean();
  42. return $output . PHP_EOL;
  43. }
  44. else {
  45. // Couldn't find template
  46. // TODO: Throw exception
  47. // TODO: test if deprecated (see: controller display())
  48. ErrorHandler::$eh->addError("Could not load template: " . $tpl);
  49. }
  50. }
  51. }
  52. ?>