1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace Fastpress\View; |
4
|
|
|
|
5
|
|
|
|
6
|
|
|
class Template{ |
7
|
|
|
private $app; |
8
|
|
|
private $data; |
9
|
|
|
private $view; |
10
|
|
|
private $block = []; |
11
|
|
|
private $layout = 'layout.html'; |
12
|
|
|
|
13
|
|
|
|
14
|
|
|
public function __construct(array $conf, $app){ |
15
|
|
|
if(empty($conf)){ |
16
|
|
|
throw new \InvalidArgumentException( |
17
|
|
|
'template class requires atleast one runtime options' |
18
|
|
|
); |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
$this->app = $app; |
22
|
|
|
$this->conf = $conf; |
|
|
|
|
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
public function render($view, array $vars = []){ |
26
|
|
|
$app = $this->app; |
27
|
|
|
if($this->view === null){ |
28
|
|
|
extract($vars, EXTR_SKIP); |
29
|
|
|
if(file_exists($view = $this->conf['template']['views'] . $view)){ |
30
|
|
|
$this->view = $view; |
31
|
|
|
require $view; |
32
|
|
|
}else{ |
33
|
|
|
|
34
|
|
|
throw new \Exception(sprintf( |
35
|
|
|
"%s template does not exist in %s ", $view, $this->conf['path'] |
36
|
|
|
)); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
} |
40
|
|
|
return $this; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
public function extend($layout){ |
44
|
|
|
$this->layout = $this->conf['template']['layout'] . $layout . '.html'; |
45
|
|
|
return $this; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
public function content($name){ |
49
|
|
|
if(array_key_exists($name, $this->block)){ |
50
|
|
|
return $this->data; |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
public function layout($layout = null, array $vars = []){ |
|
|
|
|
55
|
|
|
$layout = $layout ? $layout : $this->layout; |
56
|
|
|
$app = $this->app; |
57
|
|
|
$this->layout = $this->conf['template']['layout'] . $layout; |
58
|
|
|
return $this->layout; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
public function block($name){ |
62
|
|
|
|
63
|
|
|
$this->block[$name] = $name; |
64
|
|
|
ob_start(); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
public function endblock($name){ |
68
|
|
|
if(!array_key_exists($name, $this->block)){ |
69
|
|
|
throw new \Exception($name .' is unknown block'); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
$app = $this->app; |
73
|
|
|
$this->data = ob_get_contents(); |
74
|
|
|
ob_end_clean(); |
75
|
|
|
require $this->layout; |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: