eylmz/router

路由器 - 为PHP提供快速灵活的路由,使您能够快速轻松地构建RESTful Web应用。

v1.0.0 2017-08-19 07:35 UTC

This package is not auto-updated.

Last update: 2024-09-29 03:52:42 UTC


README

路由器 - 为PHP提供快速灵活的路由,使您能够快速轻松地构建RESTful Web应用。
版本:1.0.0

安装

您可以下载并使用它,无需任何修改。

或者使用Composer。

建议使用Composer来安装路由。

$ composer require eylmz/router

简单使用

.htaccess

Options -Indexes
Options -MultiViews
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

index.php

<?php
require 'vendor/autoload.php';
// or
// require 'src/eylmz/Router.php';

use eylmz/Router/Router;

Router::setControllerNamespace("App\\Controllers\\");
Router::setMiddlewareNamespace("App\\Middlewares\\");

// Routers
Router::any("/url","Controller@Method");
// or
Router::any("/url2",function() {

});
// #Routers

Router::routeNow(@$_GET["url"]);

可用的路由方法

Router::get($url, $callback);
Router::post($url, $callback);
Router::put($url, $callback);
Router::patch($url, $callback);
Router::delete($url, $callback);
Router::options($url, $callback);

使用多个路由器

Router::match("GET|POST",$url,$callback);
//or
Router::match(["GET","POST"],$url,$callback);

使用任意方法

Router::any($url,$callback);

路由参数

必需参数

Router::get("url\{id}",function($myID){
  echo "Hello " . $myID;
});

可选参数

Router::get("url\{id?}",function($myID=0){
  echo $myID;
});

控制器和方法参数

// Controller -> First Parameter
// Method -> Second Parameter
Router::get("admin\{controller}\{method}","{?}@{?}");

// or

// Custom
Router::get("admin\{method}\{controller}","{controller}@{method}");

正则表达式约束

Router::get('url/{id}', function ($myID) {
    
})->where('id', '[0-9]+');

Router::get('user/{id}/{name}', function ($myID, $name) {
    
})->where(['id' => '[0-9]+', 'name' => '[a-zA-Z]+']);

命名路由

Router::get('user/profile', function () {
    //
})->name('profile');

为命名路由生成URL

$url = Router::route("profile");

// Usage with parameters
Router::get('url/{id}/profile', function ($id) {
    
})->name('profile');

$url = Router::route('profile', ['id' => 1]);

路由分组

前缀URL

Router::prefix('admin')->group(function () {
    Router::get('users', function () {
        // new url -> /admin/users
    });
});

中间件

Router::middleware("middleware")->group(function () {
    Router::get('/', function () {
        
    });

    Router::get('url/profile', function () {
        
    });
});

使用多个中间件

Router::middleware(["middleware","middleware2"])->group(function () {
    Router::get('/', function () {
        
    });

    Router::get('url/profile', function () {
        
    });
});

许可证

MIT许可证(MIT)。请参阅许可证文件获取更多信息。