-
Notifications
You must be signed in to change notification settings - Fork 0
/
Controller.php
119 lines (102 loc) · 2.6 KB
/
Controller.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
namespace Core;
use Core\Request;
use Core\Exception;
use Core\RequestResponse;
use Core\Router;
use PDO;
/**
* Serves http request
* Uses Modules/* to process the request.
*
* @author azcraft
*/
class Controller
{
private static ?array $pdoInitData = null;
private static ?PDO $pdo = null;
private Request $request;
private Router $router;
private RequestResponse $response;
/**
* Parses the request from $_SERVER and loads the module.
* @param Router $router
*/
public function __construct(Router $router)
{
$this->router = $router;
$this->request = new Request();
}
/**
* Creates PDO connection.
* @param string $dsn
* @param string $username
* @param string $passwd
* @return void
*/
public static function usePDO(string $dsn,
string $username = null,
string $passwd = null): void
{
self::$pdoInitData = [$dsn, $username, $passwd];
}
/**
* Creates PDO connection.
* Uses data from usePDO command.
* @return void
*/
public static function initPDO() : void
{
if(count(self::$pdoInitData) < 3) return;
$dsn = self::$pdoInitData[0];
$username = self::$pdoInitData[1];
$passwd = self::$pdoInitData[2];
self::$pdo = new \PDO($dsn, $username, $passwd, [
PDO::ATTR_PERSISTENT => true
]);
self::$pdoInitData = null;
}
/**
* Returns current PDO connection or null
* @return PDO|null
*/
public static function getPDO(): ?PDO
{
if(self::$pdo == null)
self::initPDO();
return self::$pdo;
}
/**
* Executes and serves the request
* @return void
*/
public function run(): void
{
$this->response = $this->router->process($this->request);
$this->response->serve($this->request);
}
/**
* Asks the RouteTable to process the Request
* Stores and returns the response
* @return RequestResponse
*/
public function execute(): RequestResponse
{
$response = $this->router->process($this->request);
$this->response = $response;
return $response;
}
/**
* Serves stored request response
* @return void
*/
public function serve(): void
{
$this->response->serve($this->request);
}
}