Yii3 之路由篇初解

基础框架: yiisoft/app-api

0. 路由文件: /config/routes.php

1. 请求方法:

GET     : Route::get(string $pattern)
POST    : Route::post(string $pattern)
PATCH   : Route::patch(string $pattern)
PUT     : Route::put(string $pattern)
DELETE  : Route::delete(string $pattern)
HEAD    : Route::head(string $pattern)
OPTIONS : Route::options(string $pattern)
多方法   : Route::methods(array $methods, string $pattern)

2. 路由参数:

正则匹配模式

Route::get('/blog/{id:\d+}')   : 数字
Route::get('/blog/{name:\w+}') : 字符串

3. 绑定处理程序:

Route::get('/')->action([InfoController::class, 'index']);

4. 路由分组

Group::create('/blog')->routes(
    Route::get('/{id:\d+}')->action([BlogController::class, 'view']),
    Route::get('/')->action([BlogController::class, 'index']),
    Route::post('/')->action([BlogController::class, 'create']),
    Route::put('/{id:\d+}')->action([BlogController::class, 'update']),
    Route::delete('/{id:\d+}')->action([BlogController::class, 'delete']),
),

5. 中间件

  • 可以在/config/common/router.php中指定全局中间件
<?php

declare(strict_types=1);

use App\Middleware\ExceptionMiddleware;
use Yiisoft\Config\Config;
use Yiisoft\DataResponse\Middleware\FormatDataResponse;
use Yiisoft\Request\Body\RequestBodyParser;
use Yiisoft\Router\Group;
use Yiisoft\Router\RouteCollection;
use Yiisoft\Router\RouteCollectionInterface;
use Yiisoft\Router\RouteCollectorInterface;

/** @var Config $config */

return [
    RouteCollectionInterface::class => static function (RouteCollectorInterface $collector) use ($config) {
        $collector
            ->middleware(RequestBodyParser::class)
            ->middleware(FormatDataResponse::class)
            ->middleware(ExceptionMiddleware::class)
            ->addGroup(Group::create()->routes(...$config->get('routes')));

        return new RouteCollection($collector);
    },
];
  • 也可以在单个路由中添加或禁用一个中间件
Route::post('/logout/')
    ->action([AuthController::class, 'logout'])
    ->middleware(\Yiisoft\Auth\Middleware\Authentication::class)
    ->disableMiddleware(\App\Middleware\ExceptionMiddleware::class)