devcoder-xyz / php-router
一款灵活高效的PHP路由解决方案,旨在简化PHP应用程序中的路由管理。
Requires
- php: >=7.4
- psr/http-factory: ^1.0
- psr/http-message: ^1.0
- psr/http-server-middleware: ^1.0
Requires (Dev)
- phpunit/phpunit: ^9.5
This package is auto-updated.
Last update: 2024-08-31 00:32:20 UTC
README
描述
PHP Router 是一个简单高效的PHP应用程序路由库。它提供了一种直接的方式来定义路由、处理HTTP请求和生成URL。它基于PSR-7消息实现,能够无缝集成到PHP应用程序中。
安装
您可以通过Composer安装PHP Router。只需运行
Composer Require
composer require devcoder-xyz/php-router
要求
- PHP版本7.4或更高
- 在您的Web服务器上启用URL重写
- 可选:PSR-7 HTTP消息包(例如,guzzlehttp/psr7)
使用
-
定义路由:使用PHP Router提供的
Route
类定义路由。 -
初始化路由器:使用定义的路由初始化
Router
类。 -
匹配请求:将传入的HTTP请求匹配到定义的路由。
-
处理请求:通过执行适当的控制器或处理程序来处理匹配的路由。
-
生成URL:为命名路由生成URL。
示例
<?php class IndexController { public function __invoke() { return 'Hello world!!'; } } class ArticleController { public function getAll() { // db get all post return json_encode([ ['id' => 1], ['id' => 2], ['id' => 3] ]); } public function get(int $id) { // db get post by id return json_encode(['id' => $id]); } public function put(int $id) { // db edited post by id return json_encode(['id' => $id]); } public function post() { // db create post return json_encode(['id' => 4]); } }
// Define your routes $routes = [ new \DevCoder\Route('home_page', '/', [IndexController::class]), new \DevCoder\Route('api_articles_collection', '/api/articles', [ArticleController::class, 'getAll']), new \DevCoder\Route('api_articles', '/api/articles/{id}', [ArticleController::class, 'get']), ]; // Initialize the router $router = new \DevCoder\Router($routes, 'https://'); try { // Match incoming request $route = $router->match(ServerRequestFactory::fromGlobals()); // Handle the matched route $handler = $route->getHandler(); $attributes = $route->getAttributes(); $controllerName = $handler[0]; $methodName = $handler[1] ?? null; $controller = new $controllerName(); // Invoke the controller method if (!is_callable($controller)) { $controller = [$controller, $methodName]; } echo $controller(...array_values($attributes)); } catch (\DevCoder\Exception\MethodNotAllowed $exception) { header("HTTP/1.0 405 Method Not Allowed"); exit(); } catch (\DevCoder\Exception\RouteNotFound $exception) { header("HTTP/1.0 404 Not Found"); exit(); }
特性
- 轻量级且易于使用
- 支持基于HTTP方法的路由
- 具有属性约束的灵活路由定义
- 处理不允许的方法和找不到路由的异常情况
路由定义
可以使用PHP Router提供的Route
类定义路由。您可以为每个路由指定HTTP方法、属性约束和处理程序方法。
$route = new \DevCoder\Route('api_articles_post', '/api/articles', [ArticleController::class, 'post'], ['POST']); $route = new \DevCoder\Route('api_articles_put', '/api/articles/{id}', [ArticleController::class, 'put'], ['PUT']);
使用静态方法简化路由定义
为了使路由定义更加简单和直观,RouteTrait
提供了用于创建不同类型HTTP路由的静态方法。以下是使用方法
方法 get()
/** * Creates a new GET route with the given name, path, and handler. * * @param string $name The name of the route. * @param string $path The path of the route. * @param mixed $handler The handler for the route. * @return BaseRoute The newly created GET route. */ public static function get(string $name, string $path, $handler): BaseRoute { return new BaseRoute($name, $path, $handler); }
示例用法
$route = Route::get('home', '/', [HomeController::class, 'index']);
方法 post()
/** * Creates a new POST route with the given name, path, and handler. * * @param string $name The name of the route. * @param string $path The path of the route. * @param mixed $handler The handler for the route. * @return BaseRoute The newly created POST route. */ public static function post(string $name, string $path, $handler): BaseRoute { return new BaseRoute($name, $path, $handler, ['POST']); }
示例用法
$route = Route::post('submit_form', '/submit', [FormController::class, 'submit']);
方法 put()
/** * Creates a new PUT route with the given name, path, and handler. * * @param string $name The name of the route. * @param string $path The path of the route. * @param mixed $handler The handler for the route. * @return BaseRoute The newly created PUT route. */ public static function put(string $name, string $path, $handler): BaseRoute { return new BaseRoute($name, $path, $handler, ['PUT']); }
示例用法
$route = Route::put('update_item', '/item/{id}', [ItemController::class, 'update']);
方法 delete()
/** * Creates a new DELETE route with the given name, path, and handler. * * @param string $name The name of the route. * @param string $path The path of the route. * @param mixed $handler The handler for the route. * @return BaseRoute The newly created DELETE route. */ public static function delete(string $name, string $path, $handler): BaseRoute { return new BaseRoute($name, $path, $handler, ['DELETE']); }
示例用法
$route = Route::delete('delete_item', '/item/{id}', [ItemController::class, 'delete']);
使用这些静态方法,定义路由变得轻而易举,为您在PHP应用程序中处理路由提供了一种更顺畅、更有效的方法。
在路由对象中使用 where
约束
路由对象允许您使用where
方法定义路由参数的约束。这些约束根据正则表达式验证和过滤参数值。以下是使用方法
方法 whereNumber()
此方法将数字约束应用于指定的路由参数。
/** * Sets a number constraint on the specified route parameters. * * @param mixed ...$parameters The route parameters to apply the constraint to. * @return self The updated Route instance. */ public function whereNumber(...$parameters): self { $this->assignExprToParameters($parameters, '[0-9]+'); return $this; }
示例用法
$route = (new Route('example', '/example/{id}'))->whereNumber('id');
方法 whereSlug()
此方法将slug约束应用于指定的路由参数,允许字母数字字符和连字符。
/** * Sets a slug constraint on the specified route parameters. * * @param mixed ...$parameters The route parameters to apply the constraint to. * @return self The updated Route instance. */ public function whereSlug(...$parameters): self { $this->assignExprToParameters($parameters, '[a-z0-9-]+'); return $this; }
示例用法
$route = (new Route('article', '/article/{slug}'))->whereSlug('slug');
方法 whereAlphaNumeric()
此方法将字母数字约束应用于指定的路由参数。
/** * Sets an alphanumeric constraint on the specified route parameters. * * @param mixed ...$parameters The route parameters to apply the constraint to. * @return self The updated Route instance. */ public function whereAlphaNumeric(...$parameters): self { $this->assignExprToParameters($parameters, '[a-zA-Z0-9]+'); return $this; }
示例用法
$route = (new Route('user', '/user/{username}'))->whereAlphaNumeric('username');
方法 whereAlpha()
此方法将字母约束应用于指定的路由参数。
/** * Sets an alphabetic constraint on the specified route parameters. * * @param mixed ...$parameters The route parameters to apply the constraint to. * @return self The updated Route instance. */ public function whereAlpha(...$parameters): self { $this->assignExprToParameters($parameters, '[a-zA-Z]+'); return $this; }
示例用法
$route = (new Route('category', '/category/{name}'))->whereAlpha('name');
方法 where()
此方法允许您为指定的路由参数定义自定义约束。
/** * Sets a custom constraint on the specified route parameter. * * @param string $parameter The route parameter to apply the constraint to. * @param string $expression The regular expression constraint. * @return self The updated Route instance. */ public function where(string $parameter, string $expression): self { $this->wheres[$parameter] = $expression; return $this; }
示例用法
$route = (new Route('product', '/product/{code}'))->where('code', '\d{4}');
通过使用这些where
方法,您可以对路由参数应用精确的约束,确保输入值的正确验证。
生成URL
使用generateUri
方法为命名路由生成URL。
echo $router->generateUri('home_page'); // / echo $router->generateUri('api_articles', ['id' => 1]); // /api/articles/1 echo $router->generateUri('api_articles', ['id' => 1], true); // https:///api/articles/1
PHP Router非常适合小型到中型项目,它为处理PHP应用程序的路由任务提供了简单性和效率。