@@ -13,9 +13,9 @@ composer require devcoder-xyz/php-router
1313
1414## Requirements
1515
16- * PHP version 7.3
16+ * PHP version 7.4
1717* Enable URL rewriting on your web server
18- * Need package for PSR-7 HTTP Message
18+ * Optional : Need package for PSR-7 HTTP Message
1919 (example : guzzlehttp/psr7 )
2020
2121** How to use ?**
@@ -61,42 +61,48 @@ class ArticleController {
6161 }
6262}
6363
64- $router = new \DevCoder\Router( [
64+ $routes = [
6565 new \DevCoder\Route('home_page', '/', [IndexController::class]),
6666 new \DevCoder\Route('api_articles_collection', '/api/articles', [ArticleController::class, 'getAll']),
6767 new \DevCoder\Route('api_articles', '/api/articles/{id}', [ArticleController::class, 'get']),
68- ]);
68+ ];
69+ $router = new \DevCoder\Router($routes, 'http://localhost');
6970```
70- ##Example
71- $ _ SERVER [ 'REQUEST_URI' ] = '/api/articles/2'
72- $ _ SERVER [ 'REQUEST_METHOD' ] = 'GET'
71+
72+ ## Example
73+
7374``` php
7475try {
7576 // Example
77+
7678 // \Psr\Http\Message\ServerRequestInterface
77- // $route = $router->match(ServerRequestFactory::fromGlobals());
79+ $route = $router->match(ServerRequestFactory::fromGlobals());
7880 // OR
79-
81+
8082 // $_SERVER['REQUEST_URI'] = '/api/articles/2'
8183 // $_SERVER['REQUEST_METHOD'] = 'GET'
8284 $route = $router->matchFromPath($_SERVER['REQUEST_URI'], $_SERVER['REQUEST_METHOD']);
8385
84- $parameters = $route->getParameters ();
85- // $arguments = ['id' => 2]
86- $arguments = $route->getVars ();
86+ $handler = $route->getHandler ();
87+ // $attributes = ['id' => 2]
88+ $attributes = $route->getAttributes ();
8789
88- $controllerName = $parameters [0];
89- $methodName = $parameters [1] ?? null;
90+ $controllerName = $handler [0];
91+ $methodName = $handler [1] ?? null;
9092
9193 $controller = new $controllerName();
9294 if (!is_callable($controller)) {
9395 $controller = [$controller, $methodName];
9496 }
9597
96- echo $controller(...array_values($arguments ));
98+ echo $controller(...array_values($attributes ));
9799
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) {
99104 header("HTTP/1.0 404 Not Found");
105+ exit();
100106}
101107```
102108How to Define Route methods
@@ -115,8 +121,11 @@ echo $router->generateUri('home_page');
115121// /
116122echo $router->generateUri('api_articles', ['id' => 1]);
117123// /api/articles/1
124+
125+ echo $router->generateUri('api_articles', ['id' => 1], true);
126+ // http://localhost/api/articles/1
118127```
119128
120- Ideal for small project
129+ Ideal for small project.
121130Simple and easy!
122131[ https://github.com/devcoder-xyz/php-router ] ( https://github.com/devcoder-xyz/php-router )
0 commit comments