dariorieke/router

该软件包的最新版本(dev-master)没有提供许可信息。

使用正则表达式解析URL参数的php路由器

dev-master 2020-12-05 13:06 UTC

This package is auto-updated.

Last update: 2024-09-05 21:52:04 UTC


README

一个php路由器,可以将带有命名参数的路由映射到回调函数

安装

通过composer安装

    "require": {
        "dariorieke/router": "dev-master"
    }

运行测试

使用以下命令运行测试

./vendor/bin/phpunit .\tests

用法

基本用法

使用路由器匹配路径并运行回调函数

use DarioRieke\Router\RouteCollection;
use DarioRieke\Router\Route;
use DarioRieke\Router\Router;
use DarioRieke\Router\Exception\MethodNotAllowedException;
use DarioRieke\Router\Exception\NotFoundException;

//collection of routes
$routeCollection = new RouteCollection();

//add a route to the collection
$routeCollection->add(new Route(
	//url to match
	'/home/',
	//callback to run if route is matched
	function() {
		echo "Hello World!";
	}
));

//add collection to the router
$router = new Router($routeCollection);


try {
	//match a route to a given path
	$result = $router->match('/home/', 'GET');
} 
catch (MethodNotAllowedException | NotFoundException $e) {
	//when no matching route is found a NotFoundException will be thrown
	//when the HTTP method does not match a MethodNotAllowedException will be thrown 
}

//get the callback
$callback = $result->getCallback();
//run it
$callback();

使用URL参数的用法

您可以使用正则表达式使用URL参数

$routeCollection->add(new Route(
	//url to match with a named parameter
	'/api/user/{username}/',
	//callback to run if route is matched
	function($username) {
		echo "Hello $username!";
	}
));

要获取参数值,请使用RoutingResult

$result = $router->match('/api/user/Administrator3000/');

//get all parameters from the url 
$routeParameters = $result->getArguments();

//get the callback
$callback = $result->getCallback();

//run the callback with the parameter from the route
$callback($routeParameters['username']);

您还可以使用Route构造函数的第三个参数为您的参数提供自定义正则表达式模式。如果模式与任何路由不匹配,将抛出NotFoundException

$routeCollection->add(new Route(
	//url to match with a named parameter
	'/api/user/{username}/',
	//callback to run if route is matched
	function($username) {
		echo "Hello $username!";
	},
	[
		//now the route will only match letters of the alphabet
		'username' => '[a-zA-Z]+'
	]
));

不同的HTTP方法

路由构造函数的最后一个参数是允许的HTTP方法数组

$routeCollection->add(new Route(
	//url to match with a named parameter
	'/api/user/{username}/',
	//callback to run if route is matched
	function($username) {
		echo "Hello $username!";
	},
	[
		//now the route will only match letters of the alphabet
		'username' => '[a-zA-Z]+'
	],
	//only POST and HEAD are allowed
	['POST', 'HEAD']
));