app_view.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * This library provides methods for using views with MVC pattern
  5. * @package chamilo.library
  6. * @author Christian Fasanando <christian1827@gmail.com>
  7. */
  8. class ViewException extends Exception {}
  9. class View
  10. {
  11. private $data;
  12. private $template;
  13. private $layout;
  14. private $tool_path;
  15. /**
  16. * Constructor, init tool path for rendering
  17. * @param string tool name (optional)
  18. */
  19. public function __construct($toolname = '', $template_path=null)
  20. {
  21. if (!empty($toolname)) {
  22. if (isset($template_path)) {
  23. $path = $template_path.$toolname.'/';
  24. } else {
  25. $path = api_get_path(SYS_CODE_PATH).$toolname.'/';
  26. }
  27. if (is_dir($path)) {
  28. $this->tool_path = $path;
  29. } else {
  30. throw new ViewException('View::__construct() $path directory does not exist ' . $path);
  31. }
  32. }
  33. }
  34. /**
  35. * Set data sent from a controller
  36. * @param array data
  37. */
  38. public function set_data($data)
  39. {
  40. if (!is_array($data)) {
  41. throw new ViewException('View::set_data() $data must to be an array, you have sent a' . gettype( $data ));
  42. }
  43. $this->data = $data;
  44. }
  45. /**
  46. * Set layout view sent from a controller
  47. * @param string layout view
  48. */
  49. public function set_layout( $layout )
  50. {
  51. $this->layout = $layout;
  52. }
  53. /**
  54. * Set template view sent from a controller
  55. * @param string template view
  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 ViewException('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 ViewException('View::render_template() invalid file path '.$target);
  89. }
  90. }
  91. }