-
Notifications
You must be signed in to change notification settings - Fork 0
/
View.php
58 lines (50 loc) · 1.8 KB
/
View.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php
namespace sigawa\mvccore;
use Exception;
use sigawa\mvccore\exception\NotFoundException;
class View
{
public string $title = 'Karibu';
public function renderView($view, array $params, $layoutDirectory = '')
{
try {
$layoutName = Application::$app->layout;
if (!empty($layoutDirectory)) {
$layoutName = $layoutDirectory . '/' . $layoutName;
}
if (Application::$app->controller) {
$controllerLayout = Application::$app->controller->layout;
if (!empty($layoutDirectory)) {
$controllerLayout = $layoutDirectory . '/' . $controllerLayout;
}
$layoutName = $controllerLayout;
}
$viewContent = $this->renderViewOnly($view, $params);
ob_start();
include_once Application::$ROOT_DIR."/views/layouts/$layoutName.php";
$layoutContent = ob_get_clean();
return str_replace('{{content}}', $viewContent, $layoutContent);
} catch (Exception $e) {
throw new Exception($e->getMessage());
}
}
public function renderViewOnly($view, array $params)
{
try {
foreach ($params as $key => $value) {
$$key = $value;
}
$viewFile = Application::$ROOT_DIR . "/views/$view.php";
if (!file_exists($viewFile)) {
throw new Exception("View file '$view.php' not found.");
}
ob_start();
include_once $viewFile;
return ob_get_clean();
} catch (Exception $e) {
// You can customize the error handling here
// For example, throw a custom NotFoundException
throw new Exception($e->getMessage());
}
}
}