app_view.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. /* For licensing terms, see /dokeos_license.txt */
  3. /**
  4. * This library provides methods for using views with MVC pattern
  5. * @package dokeos.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 = '') {
  19. if (!empty($toolname)) {
  20. $path = api_get_path(SYS_CODE_PATH).$toolname.'/';
  21. if (is_dir($path)) {
  22. $this->tool_path = $path;
  23. } else {
  24. throw new ViewException('View::__construct() $path directory does not exist ' . $path);
  25. }
  26. }
  27. }
  28. /**
  29. * Set data sent from a controller
  30. * @param array data
  31. */
  32. public function set_data($data) {
  33. if (!is_array($data)) {
  34. throw new ViewException('View::set_data() $data must to be an array, you have sent a' . gettype( $data ));
  35. }
  36. $this->data = $data;
  37. }
  38. /**
  39. * Set layout view sent from a controller
  40. * @param string layout view
  41. */
  42. public function set_layout( $layout ) {
  43. $this->layout = $layout;
  44. }
  45. /**
  46. * Set template view sent from a controller
  47. * @param string template view
  48. */
  49. public function set_template($template) {
  50. $this->template = $template;
  51. }
  52. /**
  53. * Render data to the template and layout views
  54. */
  55. public function render() {
  56. $content = $this->render_template();
  57. $target = $this->tool_path.$this->layout.'.php';
  58. if (file_exists($target)) {
  59. require_once $target;
  60. } else {
  61. throw new ViewException('View::render() invalid file path '.$target);
  62. }
  63. }
  64. /**
  65. * It's used into render method for rendering data the template and layout views
  66. */
  67. private function render_template() {
  68. $target = $this->tool_path.$this->template.'.php';
  69. if (file_exists($target)) {
  70. ob_start();
  71. @extract($this->data, EXTR_OVERWRITE);
  72. require_once $target;
  73. $content = ob_get_clean();
  74. return $content;
  75. } else {
  76. throw new ViewException('View::render_template() invalid file path '.$target);
  77. }
  78. }
  79. }
  80. ?>