ctyurk15 / molot-router
简单且轻量级的PHP路由器
dev-master
2022-06-11 15:26 UTC
Requires
- php: >=5.4.0
Requires (Dev)
- phpunit/phpunit: ^7.2
This package is auto-updated.
Last update: 2024-09-11 20:37:05 UTC
README
简单的PHP路由器。
安装
要安装此包,您需要
- 安装composer
- 将以下行添加到项目文件夹中的composer.json文件中
"minimum-stability": "dev"
- 使用控制台进入您的项目文件夹
- 写下以下命令
composer require ctyurk15/molot-router
示例
<?php include "vendor/autoload.php"; use MolotRouter\Router as Router; use MolotRouter\URL as URL; use MolotRouter\Route as Route; //creating routemap. here can be instances for Route class too $routes = [ [ 'pattern' => '/', 'method' => 'GET', 'action' => 'Class1@home' ], [ 'pattern' => '/product/{id}', 'method' => 'GET', 'action' => 'Class1@product' ], [ 'pattern' => '/product', 'method' => 'POST', 'action' => 'Class1@add_product' ], ]; //some kind of controller class Class1 { public function home() { echo 'home<hr>'; } public function product($id) { echo 'Product '.$id.'<hr>'; } public function not_found() { echo '404<hr>'; } } //initializing current url $url = new URL($_SERVER['REQUEST_URI']); //initializing route //Class1@not_found will be returned if router won`t find any routes $router = new Router($routes, ['', '', 'Class1@not_found']); //getting current route $route = $router->getRoute($url, $_SERVER['REQUEST_METHOD']); //executing his action $route->execute();
!!! 重要 !!!
您应该将所有请求重定向到执行路由器的文件。例如,.htaccess代码
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /index.php [L,QSA]