View.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. class View{
  3. private $_view,$_variables,$_cssFiles,$_jsFiles;
  4. public function __construct($view, $variables=array()) {
  5. $this->_view=$view;
  6. if (isset($variables['this']))
  7. throw new Exception("'this' is a reserved variable index");
  8. $this->_variables=$variables;
  9. $this->_cssFiles=array();
  10. $this->_jsFiles=array();
  11. }
  12. // This is here to force the IConvertible interface use
  13. private static function DoConversion(IConvertible $converter, $item){
  14. return $converter->Convert($item);
  15. }
  16. public function GetHTMLFromTemplate($template) {
  17. $viewContent=file_get_contents('View/'.$this->_view);
  18. $htmlParts=array();
  19. // Make the sent variables available to the view
  20. foreach ($this->_variables as $var=>$value)
  21. eval('$'.$var.'=$this->_variables[\''.$var.'\'];'.PHP_EOL);
  22. // Break the view up to be applied to the template
  23. $matches=array();
  24. preg_match_all('/@(.*)\{(.*)\}@/sU', $viewContent,$matches);
  25. for ($i=0;$i<count($matches[0]);$i++)
  26. $htmlParts[$matches[1][$i]]=$matches[2][$i];
  27. // Populate the template
  28. $templateHTML=file_get_contents($template);
  29. $code=preg_replace_callback("/\{@(.*)\}/", function($match) use ($htmlParts){
  30. if (isset($htmlParts[$match[1]]))
  31. return $htmlParts[$match[1]];
  32. return "";
  33. }, $templateHTML);
  34. // Process the new PHP
  35. //file_put_contents("output.php", $code);
  36. ob_start();
  37. eval('?>'.$code.'<?php ');
  38. $output=ob_get_clean();
  39. // Do the convertible tags
  40. $output=preg_replace_callback('/<convertible type="(.*)">(.*)<\/convertible>/sU', function($match) {
  41. if (class_exists($match[1],false))
  42. return self::DoConversion(new $match[1](), $match[2]);
  43. return $match[2];
  44. }, $output);
  45. return $output;
  46. }
  47. public function RegisterCSSFile($path){
  48. $this->_cssFiles[]=$path;
  49. }
  50. public function GetCSSFiles() {
  51. return $this->_cssFiles;
  52. }
  53. public function RegisterJSFile($path){
  54. $this->_jsFiles[]=$path;
  55. }
  56. public function GetJSFiles() {
  57. return $this->_jsFiles;
  58. }
  59. }