NanoFramework 1.4.0
A tiny PHP Framework
Controller.php
Go to the documentation of this file.
1<?php
2
4
6
12abstract class Controller
13{
17 protected $data = [];
18
22 protected $rawData = [];
23
27 public function __construct()
28 {
29 }
30
38 protected function fragment(string $page): string
39 {
40 if ('.html' != \substr($page, -5)) {
41 $page .= '.html';
42 }
43 $view = new View();
44
45 return $view->parseFile(APPPATH . DIRECTORY_SEPARATOR . 'Views' . DIRECTORY_SEPARATOR . $page, $this->data, $this->rawData);
46 }
47
51 protected function render(): void
52 {
53 $caller = debug_backtrace(0, 2)[1];
54 $classParts = explode('\\', $caller['class']);
55 $page = strtolower(end($classParts)) . DIRECTORY_SEPARATOR . $caller['function'];
56
57 $fragment = $this->fragment($page);
58
59 $this->rawData['template_content'] = $fragment;
60 $siteName = DotEnv::getEnv('SITE_NAME') ?? 'change SITE_NAME in .env';
61 $this->data['template_title'] = array_key_exists('page_title', $this->data) ? $this->data['page_title'] . ' — ' . $siteName : $siteName;
62
63 $template = $this->fragment('template.html');
64
65 echo $template;
66 }
67
73 protected function getMethod(): string
74 {
75 return strtolower($_SERVER['REQUEST_METHOD']);
76 }
77
83 protected function isPost(): bool
84 {
85 return 'post' == $this->getMethod();
86 }
87
93 protected function isGet(): bool
94 {
95 return 'get' == $this->getMethod();
96 }
97
103 protected function isAjax(): bool
104 {
105 return 'xmlhttprequest' == strtolower($_SERVER['HTTP_X_REQUESTED_WITH'] ?? '');
106 }
107
119 protected function getPost(?string $element = null)
120 {
121 if (null === $element) {
122 return $_POST;
123 }
124
125 return $_POST[$element] ?? null;
126 }
127
139 protected function getGet(?string $element = null)
140 {
141 if (null === $element) {
142 return $_GET;
143 }
144
145 return $_GET[$element] ?? null;
146 }
147
155 protected function redirect(string $location): void
156 {
157 throw new Exceptions\RedirectException($location);
158 }
159
165 protected function show404(?string $message = null): void
166 {
167 header('HTTP/1.1 404 Not Found');
168 if ($message) {
169 echo $message;
170 }
171
172 throw new Error404Exception($message ?? '');
173 }
174}
Handles I/O and HTTP methods.
Definition: Controller.php:13
show404(?string $message=null)
Definition: Controller.php:165
getPost(?string $element=null)
Definition: Controller.php:119
getGet(?string $element=null)
Definition: Controller.php:139
static getEnv(string $key)
Definition: DotEnv.php:74
Parses files to insert data.
Definition: View.php:11