kreme201 / file-base-router
基于文件的 PHP 路由器
0.1.0
2024-02-28 09:00 UTC
Requires
- php: >=8.3
Requires (Dev)
- mikey179/vfsstream: ^1.6
- phpunit/phpunit: ^11.0
README
基于文件的路由器库旨在处理基于文件的动态路由。
安装
composer require kreme201/file-base-router
已在 PHP 8.3 上开发和测试。
Apache 设置
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php [L]
用法
项目结构
.
├── pages
│ ├── board
│ │ ├── [id].php
│ │ └── index.php
│ ├── index.php
├── public
│ └── index.php
└── vendor
public/index.php
<?php require '/path/to/vendor/autoload.php'; $dispatcher = new Kreme201\FileBaseRouter\Dispatcher(dirname(__DIR__) . '/pages'); $template = $dispatcher->dispatch(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)); if (false !== $template && file_exists($template)) { include $template; } else { http_response_code(404); }
创建 Dispatcher
实例时,根据提供的路径处理路由。
可以使用 [{name}]
和 [...{name}]
处理动态路径来捕获动态数据。
可以通过 $_GET
访问每个数据,使用 [...{name}]
定义的包含所有子路径的数据。
/: {base_path}/index.php
/board: {base_path}/board/index.php
/board/123: {base_path}/board/[id].php, $_GET['id'] => 123
/test/slug/example: {base_path}/test/[...slug].php, $_GET['slug'] => 'slug/example'