app_view.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. private $data;
  11. private $template;
  12. private $layout;
  13. private $tool_path;
  14. /**
  15. * Constructor, init tool path for rendering
  16. * @param string tool name (optional)
  17. */
  18. public function __construct($toolname = '', $template_path=null) {
  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 ViewException('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. if (!is_array($data)) {
  38. throw new ViewException('View::set_data() $data must to be an array, you have sent a' . gettype( $data ));
  39. }
  40. $this->data = $data;
  41. }
  42. /**
  43. * Set layout view sent from a controller
  44. * @param string layout view
  45. */
  46. public function set_layout( $layout ) {
  47. $this->layout = $layout;
  48. }
  49. /**
  50. * Set template view sent from a controller
  51. * @param string template view
  52. */
  53. public function set_template($template) {
  54. $this->template = $template;
  55. }
  56. /**
  57. * Render data to the template and layout views
  58. */
  59. public function render() {
  60. $content = $this->render_template();
  61. $target = $this->tool_path.$this->layout.'.php';
  62. if (file_exists($target)) {
  63. require_once $target;
  64. } else {
  65. throw new ViewException('View::render() invalid file path '.$target);
  66. }
  67. }
  68. /**
  69. * It's used into render method for rendering data in the template and layout views
  70. * @return String Rendered template (as HTML, most of the time)
  71. */
  72. private function render_template() {
  73. $target = $this->tool_path.$this->template.'.php';
  74. if (file_exists($target)) {
  75. ob_start();
  76. @extract($this->data, EXTR_OVERWRITE); //pass the $this->data array into local scope
  77. require_once $target;
  78. $content = ob_get_clean();
  79. return $content;
  80. } else {
  81. throw new ViewException('View::render_template() invalid file path '.$target);
  82. }
  83. }
  84. }
  85. ?>