middlewares / trailing-slash
中间件用于规范化 URI 路径的尾部斜杠
v2.0.1
2020-12-02 00:06 UTC
Requires
- php: ^7.2 || ^8.0
- middlewares/utils: ^3.0
- psr/http-server-middleware: ^1.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.0
- laminas/laminas-diactoros: ^2.2
- oscarotero/php-cs-fixer-config: ^1.0
- phpstan/phpstan: ^0.12
- phpunit/phpunit: ^8|^9
- squizlabs/php_codesniffer: ^3.0
README
中间件用于规范化 URI 路径的尾部斜杠。默认情况下会删除斜杠,例如,/post/23/
转换为 /post/23
。如果您在路由器方面遇到问题,则非常有用。
要求
- PHP >= 7.2
- 一个 PSR-7 http 库
- 一个 PSR-15 中间件分发器
安装
此软件包可以通过 Composer 安装并自动加载,作为 middlewares/trailing-slash。
composer require middlewares/trailing-slash
示例
$dispatcher = new Dispatcher([ (new Middlewares\TrailingSlash(true)) ->redirect() ]); $response = $dispatcher->dispatch(new ServerRequest());
用法
默认情况下,此中间件会删除 URI 路径的尾部斜杠。将构造函数的第一个参数设置为 true
以添加而不是删除
//Removes the slash, so /post/23/ is converted to /post/23 $slash = new Middlewares\TrailingSlash(); //Force the slash, so /post/23 is converted to /post/23/ $slash = new Middlewares\TrailingSlash(true);
当然,如果路径包含扩展名,则不会添加斜杠。例如,images/image.png
保持不变,而不是转换为 images/image.png/
。
重定向
如果必须转换路径,则此选项将返回一个 301
响应,重定向到新路径。您可以提供 Psr\Http\Message\ResponseFactoryInterface
,它将用于创建重定向响应。如果没有定义,将自动使用 Middleware\Utils\Factory。
$responseFactory = new MyOwnResponseFactory(); //Simply removes the slash $slash = new Middlewares\TrailingSlash(); //Returns a redirect response to the new path $slash = (new Middlewares\TrailingSlash())->redirect(); //Returns a redirect response to the new path using a specific response factory $slash = (new Middlewares\TrailingSlash())->redirect($responseFactory);
有关最近更改的更多信息,请参阅 CHANGELOG,有关贡献细节的更多信息,请参阅 CONTRIBUTING。
MIT 许可证 (MIT)。有关更多信息,请参阅 LICENSE。