|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
require_once \dirname(__DIR__) . '/vendor/autoload.php'; |
|
6
|
|
|
|
|
7
|
|
|
use Gacela\Router\Entities\Request; |
|
8
|
|
|
use Gacela\Router\Entities\Response; |
|
9
|
|
|
use Gacela\Router\Router; |
|
10
|
|
|
use Gacela\Router\Routes; |
|
11
|
|
|
|
|
12
|
|
|
# To run this example locally, you can run in your terminal: |
|
13
|
|
|
# $ composer serve |
|
14
|
|
|
|
|
15
|
|
|
class Controller |
|
16
|
|
|
{ |
|
17
|
|
|
public function __construct( |
|
18
|
|
|
private Request $request, |
|
19
|
|
|
) { |
|
20
|
|
|
} |
|
21
|
|
|
|
|
22
|
|
|
public function __invoke(): string |
|
23
|
|
|
{ |
|
24
|
|
|
$number = $this->request->get('number'); |
|
25
|
|
|
$method = $this->request->get('REQUEST_METHOD'); |
|
26
|
|
|
|
|
27
|
|
|
if (!empty($number)) { |
|
28
|
|
|
return sprintf("__invoke with %s 'number'=%d", $method, $number); |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
return '__invoke with ' . $method; |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
public function customAction(int $number = 0): string |
|
35
|
|
|
{ |
|
36
|
|
|
return "customAction(number: {$number})"; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
public function customHeaders(): Response |
|
40
|
|
|
{ |
|
41
|
|
|
return new Response('{"custom": "headers"}', [ |
|
42
|
|
|
'Access-Control-Allow-Origin: *', |
|
43
|
|
|
'Content-Type: application/json', |
|
44
|
|
|
]); |
|
45
|
|
|
} |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
Router::configure(static function (Routes $routes): void { |
|
49
|
|
|
# Try it out: http://localhost:8081/docs |
|
50
|
|
|
$routes->redirect('docs', 'https://gacela-project.com/'); |
|
51
|
|
|
|
|
52
|
|
|
# Try it out: http://localhost:8081?number=456 |
|
53
|
|
|
$routes->match(['GET', 'POST'], '/', Controller::class); |
|
54
|
|
|
|
|
55
|
|
|
# Try it out: http://localhost:8081/custom/123 |
|
56
|
|
|
$routes->get('custom/{number}', Controller::class, 'customAction'); |
|
57
|
|
|
|
|
58
|
|
|
# Try it out: http://localhost:8081/custom |
|
59
|
|
|
$routes->any('custom', Controller::class); |
|
60
|
|
|
|
|
61
|
|
|
# Try it out: http://localhost:8081/headers |
|
62
|
|
|
$routes->any('headers', Controller::class, 'customHeaders'); |
|
63
|
|
|
}); |
|
64
|
|
|
|