niirrty / niirrty.routing
一个PHP路由库。
0.6.2
2024-02-22 09:08 UTC
Requires
- php: >=8.1
README
路由库
安装
在composer.json
内部
{ "require": { "php": ">=8.1", "niirrty/niirrty.routing": "~0.6" } }
用法
路由非常简单
首先在DOCUMENT_ROOT
内部创建一个.htaccess
文件。
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]
这意味着:所有请求非存在文件或目录都会重定向到index.php
。被调用但不存在URL路径将传递给$_SERVER[ 'REQUEST_URI' ]
。
如果你想在应用中使用此包,请包含依赖的composer autoload.php。
use \Niirrty\Routing\UrlPathLocator\RequestUri as RequestUriLocator; use \Niirrty\Routing\UrlPathLocator\ILocator; // Get the current called not existing URL path by $_SERVER[ 'REQUEST_URI' ] $urlPathLocator = new RequestUriLocator(); // Init the router and chain all required stuff $router = \Niirrty\Routing\Router::CreateInstance() // Handling URL paths, not declared by a route ->setFallBackHandler( function( ILocator $locator ) use( $twig ) { // TODO: add code for handling URL paths, not declared by a route echo 'Invalid request!'; exit; } ) // Redirect all index calls to '/' (home call) ->addMultiPathStaticRedirection( [ '/app.php', '/index.html', '/start.php', '/start.html', '/home.php', '/start.html' ], '' ) // Home call ->addSimpleRoute( '/', function( ILocator $locator ) { // TODO: show the home } ) // handling '/services/*' calls ->addRegexRoute( '~^/services/([A-Za-z0-9_.:-]+)/?$~', [ function( $matches ) { // TODO: $matches[ 1 ] defines the first part inside parenthesis, and so on echo '<pre>'; print_r( $matches ); exit; } ] ) // add an simple route for showing the impressum ->addSimpleRoute( '/impressum', function( ILocator $locator ) { // TODO: show the impressum } ); // Call the router with current locator => Done $router->call( $urlPathLocator );