1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace PHPieces\Framework; |
4
|
|
|
|
5
|
|
|
use \League\Plates\Engine; |
6
|
|
|
use League\Route\RouteCollection; |
7
|
|
|
use Zend\Diactoros\Response; |
8
|
|
|
use Zend\Diactoros\Response\SapiEmitter; |
9
|
|
|
use Zend\Diactoros\ServerRequestFactory; |
10
|
|
|
|
11
|
|
|
class App |
12
|
|
|
{ |
13
|
|
|
public $container; |
14
|
|
|
|
15
|
|
|
public $route; |
16
|
|
|
|
17
|
|
|
public function __construct($config) |
18
|
|
|
{ |
19
|
|
|
$this->config = $config; |
|
|
|
|
20
|
|
|
$this->bootstrap(); |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
public function bootstrap() |
24
|
|
|
{ |
25
|
|
|
$this->loadContainer(); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
public function run() |
29
|
|
|
{ |
30
|
|
|
$request = $this->container->get('request'); |
31
|
|
|
|
32
|
|
|
$response = $this->getResponse($request); |
33
|
|
|
|
34
|
|
|
$this->container->get('emitter')->emit($response); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
public function get($route, $handler) |
38
|
|
|
{ |
39
|
|
|
$this->route->map('GET', $route, $handler); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
public function post($route, $handler) |
43
|
|
|
{ |
44
|
|
|
$this->route->map('POST', $route, $handler); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
protected function loadContainer() |
|
|
|
|
48
|
|
|
{ |
49
|
|
|
$this->container = new \League\Container\Container; |
50
|
|
|
|
51
|
|
|
$this->container->delegate( |
52
|
|
|
new \League\Container\ReflectionContainer |
53
|
|
|
); |
54
|
|
|
|
55
|
|
|
$this->container->share('response', Response::class); |
56
|
|
|
|
57
|
|
|
$this->container->share( |
58
|
|
|
'request', |
59
|
|
|
ServerRequestFactory::fromGlobals( |
60
|
|
|
$_SERVER, |
61
|
|
|
$_GET, |
62
|
|
|
$_POST, |
63
|
|
|
$_COOKIE, |
64
|
|
|
$_FILES |
65
|
|
|
) |
66
|
|
|
); |
67
|
|
|
|
68
|
|
|
$this->container->share('emitter', SapiEmitter::class); |
69
|
|
|
|
70
|
|
|
$this->route = new RouteCollection($this->container); |
71
|
|
|
|
72
|
|
|
$this->container->share(Engine::class, Engine::class)->withArgument($this->config['template_dir']); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
public function getResponse($request) |
76
|
|
|
{ |
77
|
|
|
$response = $this->route->dispatch($request, $this->container->get('response')); |
78
|
|
|
|
79
|
|
|
return $response; |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|
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: