sevencoder / router
这是一个简单的Lib Router,使用spl autload加载类控制器
v0.0.3
2023-10-14 17:38 UTC
Requires
- php: >=7.4, <8.2
Requires (Dev)
- phpunit/phpunit: ^9.6
- symfony/var-dumper: ^5.4
This package is auto-updated.
Last update: 2024-09-16 14:02:42 UTC
README
这个库的特点:这个库有一个实现,允许您配置路由而无需指定命名空间。为此,我实现了PHP中自带的SP Autoload功能。这样,您可以定义控制器的Base Path并继续创建路由。自定义Autoload的实现将负责从基础路径开始查找控制器类,考虑子文件夹。
观察:以下步骤假设您正在使用Ubuntu系统上的Apache2。对于其他操作系统或Web服务器,可能需要进行调整。
示例:在库的安装文件夹中,有.htaccess、控制器、Postman测试json示例和一个索引文件,该索引文件将首先接收HTTP请求并调用库的资源
关于最后一个版本(v0.0.3)的说明:在这个版本中,实现了一个方法来处理通过POST表单发送的请求参数的安全性。请不要发送具有以下名称或值的参数,因为它们将被删除并清理以防止攻击:from、select、insert、delete、where、drop table、show tables、#、--。
- 要使其在Apache上工作,请按照以下步骤操作
1 - 在命令行中运行以下命令进行安装
Run the command:
composer require sevencoder/router
2 - 要在Ubuntu上的Apache2上工作,对于其他操作系统,找到等效命令。
Run the command:
sudo a2enmod rewrite
3 - 要生效,使用以下命令重启Apache2
Run the command:
sudo systemctl restart apache2
4 - 在受影响的文件夹中配置一个.htaccess文件。.htaccess文件的内容应该是
RewriteEngine On
Options All -Indexes
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?route=$1 [L,QSA]
5 - 接收http请求的文件示例,配置路由并调用dispatch
<?php require 'vendor/autoload.php'; use SevenCoder\Router\Router; /* this is the separator of class and method(of class controller) */ $separator = '@'; /* this is project url, you can define it here or get it from elsewhere */ $projectUrl = 'https:///router'; $router = new Router($projectUrl, $separator); /* base directory that get controller */ $baseDir = __DIR__.'/App/Controller'; /* set the base controller */ $router->setBasePath($baseDir); $router->get('/', 'HomeController@helloWorld'); $router->get('test/{teste}/{teste2}', 'HomeController@testGet'); $router->post('test-post', 'HomeController@testPost'); $router->put('test-put', 'HomeController@testPut'); $router->patch('test-patch', 'HomeController@testPatch'); $router->options('test-options', 'HomeController@testOptions'); $router->delete('test-delete', 'HomeController@testDelete'); $router->prefix('test-prefix'); $router->get('1/{param1}/{param2}', 'HomeController@testGestPrefix'); $router->get('2', 'HomeController@testGetPrefix'); $router->dispatch();