1 | <?php |
||
12 | class View |
||
13 | { |
||
14 | /** |
||
15 | * @var $template Template file or array |
||
16 | * @var $templateData Data to send to template file |
||
17 | * @var $sortOrder For sorting views |
||
18 | * @var $type Type of view |
||
19 | */ |
||
20 | private $template; |
||
21 | private $templateData = []; |
||
22 | private $sortOrder; |
||
23 | private $type; |
||
24 | |||
25 | |||
26 | |||
27 | /** |
||
28 | * Set values for the view. |
||
29 | * |
||
30 | * @param array|string|callable $template the template file, array |
||
31 | * or callable |
||
32 | * @param array $data variables to make available to the |
||
33 | * view, default is empty |
||
34 | * @param integer $sort which order to display the views, |
||
35 | * if suitable |
||
36 | * @param string $type which type of view |
||
37 | * |
||
38 | * @return self |
||
39 | */ |
||
40 | 6 | public function set($template, $data = [], $sort = 0, $type = "file") |
|
85 | |||
86 | |||
87 | |||
88 | /** |
||
89 | * Render the view by its type. |
||
90 | * |
||
91 | * @param object $di optional with access to the framework resources. |
||
92 | * |
||
93 | * @return void |
||
94 | */ |
||
95 | 6 | public function render(ContainerInterface $di = null) |
|
96 | { |
||
97 | 6 | switch ($this->type) { |
|
98 | 6 | case "file": |
|
99 | if ($di->has("viewRenderFile")) { |
||
100 | $viewRender = $di->get("viewRenderFile"); |
||
|
|||
101 | } else { |
||
102 | $viewRender = new ViewRenderFile($di); |
||
103 | $viewRender->setDI($di); |
||
104 | } |
||
105 | $viewRender->render($this->template, $this->templateData); |
||
106 | break; |
||
107 | |||
108 | 6 | case "callback": |
|
109 | 4 | if (!is_callable($this->template)) { |
|
110 | throw new Exception("View is expecting a valid callback, provided callback seems to not be a callable."); |
||
111 | } |
||
112 | 4 | echo call_user_func($this->template, $this->templateData); |
|
113 | 4 | break; |
|
114 | |||
115 | 2 | case "string": |
|
116 | 1 | echo $this->template; |
|
117 | 1 | break; |
|
118 | |||
119 | 1 | case "empty": |
|
120 | break; |
||
121 | |||
122 | default: |
||
123 | 1 | throw new Exception("Not a valid template type: '{$this->type}'."); |
|
124 | } |
||
125 | 5 | } |
|
126 | |||
127 | |||
128 | |||
129 | /** |
||
130 | * Give the sort order for this view. |
||
131 | * |
||
132 | * @return int |
||
133 | */ |
||
134 | public function sortOrder() |
||
138 | } |
||
139 |
If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe: