1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
require_once \dirname(__DIR__) . '/vendor/autoload.php'; |
6
|
|
|
|
7
|
|
|
use Gacela\Router\Configure\Routes; |
8
|
|
|
use Gacela\Router\Entities\Request; |
9
|
|
|
use Gacela\Router\Entities\Response; |
10
|
|
|
use Gacela\Router\Router; |
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
|
|
|
|
26
|
|
|
if (!empty($number)) { |
27
|
|
|
return sprintf("__invoke with 'number'=%d", $number); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
return '__invoke'; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
public function customAction(int $number = 0): string |
34
|
|
|
{ |
35
|
|
|
return "customAction(number: {$number})"; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
public function customHeaders(): Response |
39
|
|
|
{ |
40
|
|
|
return new Response('{"custom": "headers"}', [ |
41
|
|
|
'Access-Control-Allow-Origin: *', |
42
|
|
|
'Content-Type: application/json', |
43
|
|
|
]); |
44
|
|
|
} |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
$router = new Router(static function (Routes $routes): void { |
48
|
|
|
# Try it out: http://localhost:8081/docs |
49
|
|
|
$routes->redirect('docs', 'https://gacela-project.com/'); |
50
|
|
|
|
51
|
|
|
# Try it out: http://localhost:8081?number=456 |
52
|
|
|
$routes->match(['GET', 'POST'], '/', Controller::class); |
53
|
|
|
|
54
|
|
|
# Try it out: http://localhost:8081/custom/123 |
55
|
|
|
$routes->get('custom/{number}', Controller::class, 'customAction'); |
56
|
|
|
|
57
|
|
|
# Try it out: http://localhost:8081/custom |
58
|
|
|
$routes->any('custom', Controller::class); |
59
|
|
|
|
60
|
|
|
# Try it out: http://localhost:8081/headers |
61
|
|
|
$routes->any('headers', Controller::class, 'customHeaders'); |
62
|
|
|
}); |
63
|
|
|
|
64
|
|
|
$router->run(); |
65
|
|
|
|