app_view.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Class View
  5. */
  6. class View
  7. {
  8. private $data;
  9. private $template;
  10. private $layout;
  11. private $tool_path;
  12. /**
  13. * Constructor, init tool path for rendering
  14. * @param string $toolname tool name (optional)
  15. * @param string $template_path
  16. */
  17. public function __construct($toolname = '', $template_path = null)
  18. {
  19. if (!empty($toolname)) {
  20. if (isset($template_path)) {
  21. $path = $template_path.$toolname.'/';
  22. } else {
  23. $path = api_get_path(SYS_CODE_PATH).$toolname.'/';
  24. }
  25. if (is_dir($path)) {
  26. $this->tool_path = $path;
  27. } else {
  28. throw new Exception('View::__construct() $path directory does not exist '.$path);
  29. }
  30. }
  31. }
  32. /**
  33. * Set data sent from a controller
  34. * @param array data
  35. */
  36. public function set_data($data)
  37. {
  38. if (!is_array($data)) {
  39. throw new Exception('View::set_data() $data must to be an array, you have sent a'.gettype($data));
  40. }
  41. $this->data = $data;
  42. }
  43. /**
  44. * Set layout view sent from a controller
  45. * @param string layout view
  46. * @param string $layout
  47. */
  48. public function set_layout($layout)
  49. {
  50. $this->layout = $layout;
  51. }
  52. /**
  53. * Set template view sent from a controller
  54. * @param string template view
  55. * @param string $template
  56. */
  57. public function set_template($template)
  58. {
  59. $this->template = $template;
  60. }
  61. /**
  62. * Render data to the template and layout views
  63. */
  64. public function render()
  65. {
  66. $content = $this->render_template();
  67. $target = $this->tool_path.$this->layout.'.php';
  68. if (file_exists($target)) {
  69. require_once $target;
  70. } else {
  71. throw new Exception('View::render() invalid file path '.$target);
  72. }
  73. }
  74. /**
  75. * It's used into render method for rendering data in the template and layout views
  76. * @return String Rendered template (as HTML, most of the time)
  77. */
  78. private function render_template()
  79. {
  80. $target = $this->tool_path.$this->template.'.php';
  81. if (file_exists($target)) {
  82. ob_start();
  83. @extract($this->data, EXTR_OVERWRITE); //pass the $this->data array into local scope
  84. require_once $target;
  85. $content = ob_get_clean();
  86. return $content;
  87. } else {
  88. throw new Exception('View::render_template() invalid file path '.$target);
  89. }
  90. }
  91. }