@@ -13,9 +13,9 @@ composer require devcoder-xyz/php-router
13
13
14
14
## Requirements
15
15
16
- * PHP version 7.3
16
+ * PHP version 7.4
17
17
* Enable URL rewriting on your web server
18
- * Need package for PSR-7 HTTP Message
18
+ * Optional : Need package for PSR-7 HTTP Message
19
19
(example : guzzlehttp/psr7 )
20
20
21
21
** How to use ?**
@@ -61,42 +61,48 @@ class ArticleController {
61
61
}
62
62
}
63
63
64
- $router = new \DevCoder\Router( [
64
+ $routes = [
65
65
new \DevCoder\Route('home_page', '/', [IndexController::class]),
66
66
new \DevCoder\Route('api_articles_collection', '/api/articles', [ArticleController::class, 'getAll']),
67
67
new \DevCoder\Route('api_articles', '/api/articles/{id}', [ArticleController::class, 'get']),
68
- ]);
68
+ ];
69
+ $router = new \DevCoder\Router($routes, 'http://localhost');
69
70
```
70
- ##Example
71
- $ _ SERVER [ 'REQUEST_URI' ] = '/api/articles/2'
72
- $ _ SERVER [ 'REQUEST_METHOD' ] = 'GET'
71
+
72
+ ## Example
73
+
73
74
``` php
74
75
try {
75
76
// Example
77
+
76
78
// \Psr\Http\Message\ServerRequestInterface
77
- // $route = $router->match(ServerRequestFactory::fromGlobals());
79
+ $route = $router->match(ServerRequestFactory::fromGlobals());
78
80
// OR
79
-
81
+
80
82
// $_SERVER['REQUEST_URI'] = '/api/articles/2'
81
83
// $_SERVER['REQUEST_METHOD'] = 'GET'
82
84
$route = $router->matchFromPath($_SERVER['REQUEST_URI'], $_SERVER['REQUEST_METHOD']);
83
85
84
- $parameters = $route->getParameters ();
85
- // $arguments = ['id' => 2]
86
- $arguments = $route->getVars ();
86
+ $handler = $route->getHandler ();
87
+ // $attributes = ['id' => 2]
88
+ $attributes = $route->getAttributes ();
87
89
88
- $controllerName = $parameters [0];
89
- $methodName = $parameters [1] ?? null;
90
+ $controllerName = $handler [0];
91
+ $methodName = $handler [1] ?? null;
90
92
91
93
$controller = new $controllerName();
92
94
if (!is_callable($controller)) {
93
95
$controller = [$controller, $methodName];
94
96
}
95
97
96
- echo $controller(...array_values($arguments ));
98
+ echo $controller(...array_values($attributes ));
97
99
98
- } catch (\Exception $exception) {
100
+ } catch (\DevCoder\Exception\MethodNotAllowed $exception) {
101
+ header("HTTP/1.0 405 Method Not Allowed");
102
+ exit();
103
+ } catch (\DevCoder\Exception\RouteNotFound $exception) {
99
104
header("HTTP/1.0 404 Not Found");
105
+ exit();
100
106
}
101
107
```
102
108
How to Define Route methods
@@ -115,8 +121,11 @@ echo $router->generateUri('home_page');
115
121
// /
116
122
echo $router->generateUri('api_articles', ['id' => 1]);
117
123
// /api/articles/1
124
+
125
+ echo $router->generateUri('api_articles', ['id' => 1], true);
126
+ // http://localhost/api/articles/1
118
127
```
119
128
120
- Ideal for small project
129
+ Ideal for small project.
121
130
Simple and easy!
122
131
[ https://github.com/devcoder-xyz/php-router ] ( https://github.com/devcoder-xyz/php-router )
0 commit comments