中间件(六)

作者: 寒云暮雨 | 来源:发表于2019-10-14 13:27 被阅读0次

为什么要定义中间件,定义中间件有什么好处?
1、定义一个中间件
执行一下命令定义中间件,在我们的项目中就产生一个中间件,如下图

php artisan make:middleware Log

在中间件中记录请求的路由地址

<?php

namespace App\Http\Middleware;

use Closure;

class Log
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        \Illuminate\Support\Facades\Log::info('log', [$request->fullUrl()]);
        return $next($request);
    }
}

2、注册一个中间
项目中所有的中间件都在F:\web\learnLaravel\app\Http\Kernel.php中,我们要注册一个中间件,只需要将我们的中间件注入即可

<?php

namespace App\Http;

use App\Http\Middleware\Log;
use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \App\Http\Middleware\TrustProxies::class,
        \App\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'log' => Log::class,//我们定义的写请求日志的中间件
    ];

    /**
     * The priority-sorted list of middleware.
     *
     * This forces non-global middleware to always be in the given order.
     *
     * @var array
     */
    protected $middlewarePriority = [
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\Authenticate::class,
        \Illuminate\Routing\Middleware\ThrottleRequests::class,
        \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \Illuminate\Auth\Middleware\Authorize::class,
    ];
}

我们将我们的中间件放入$routeMiddleware数组当中,我们注册了一个中间件
3、如何使用一个中间件
修改我们的路由

Route::get('/', 'IndexController@index');
Route::get('/register', 'IndexController@register')->name('register');
Route::get('/user/{userId}', 'IndexController@getUseById')->where('userId', '[0-9]+')->middleware('log');
Route::group(['middleware' => ['auth'], 'prefix' => 'group/prefix'], function () {
    Route::get('/user/{userId}', 'IndexController@getUseById')->where('userId', '[0-9]+');
});

我们在这个路由上添加中间件

Route::get('/user/{userId}', 'IndexController@getUseById')->where('userId', '[0-9]+')->middleware('log');

访问一下http://127.0.0.1:8000/user/1,打开我们的工程,会在日志目录下生成一条日志,如下图所示

image.png
4、路由分组增加中间件
调整我们的路由如下
Route::get('/', 'IndexController@index');
Route::get('/register', 'IndexController@register')->name('register');
Route::get('/user/{userId}', 'IndexController@getUseById')->where('userId', '[0-9]+');
Route::group(['middleware' => ['log'], 'prefix' => 'group/prefix'], function () {
    Route::get('/user/{userId}', 'IndexController@getUseById')->where('userId', '[0-9]+');
});

我们给路由组增加了log中间件

Route::group(['middleware' => ['log'], 'prefix' => 'group/prefix'], function () {
    Route::get('/user/{userId}', 'IndexController@getUseById')->where('userId', '[0-9]+');
});

我们访问http://127.0.0.1:8000/group/prefix/user/1,就会在我们日志中记录我们访问的路由地址

image.png
5、整个路由文件增加中间件
F:\web\learnLaravel\app\Providers\RouteServiceProvider.php文件定义了我们所有的路由
<?php

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Route;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * This namespace is applied to your controller routes.
     *
     * In addition, it is set as the URL generator's root namespace.
     *
     * @var string
     */
    protected $namespace = 'App\Http\Controllers\Web';

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        //

        parent::boot();
    }

    /**
     * Define the routes for the application.
     *
     * @return void
     */
    public function map()
    {
        $this->mapApiRoutes();

        $this->mapWebRoutes();

        //
    }

    /**
     * Define the "web" routes for the application.
     *
     * These routes all receive session state, CSRF protection, etc.
     *
     * @return void
     */
    protected function mapWebRoutes()
    {
        Route::middleware('web')
            ->middleware('log')
             ->namespace($this->namespace)
             ->group(base_path('routes/web.php'));
    }

    /**
     * Define the "api" routes for the application.
     *
     * These routes are typically stateless.
     *
     * @return void
     */
    protected function mapApiRoutes()
    {
        Route::prefix('api')
             ->middleware('api')
             ->namespace($this->namespace)
             ->group(base_path('routes/api.php'));
    }
}

我们在mapWebRoutes方法中,引入了中间件
protected function mapWebRoutes() { Route::middleware('web') ->middleware('log') ->namespace($this->namespace) ->group(base_path('routes/web.php')); }
更改我们的路由

Route::get('/', 'IndexController@index');
Route::get('/register', 'IndexController@register')->name('register');
Route::get('/user/{userId}', 'IndexController@getUseById')->where('userId', '[0-9]+');
Route::group(['prefix' => 'group/prefix'], function () {
    Route::get('/user/{userId}', 'IndexController@getUseById')->where('userId', '[0-9]+');
});

那么我们访问web下面任何一个路由地址都会产生一条日志

相关文章

  • 中间件(六)

    为什么要定义中间件,定义中间件有什么好处?1、定义一个中间件执行一下命令定义中间件,在我们的项目中就产生一个中间件...

  • 翻译

    Laravel 的路由中间件 简介 创建中间件 注册中间件全局中间件为路由指定中间件中间件组 中间件参数 Term...

  • 中间件学习——具体分类

    中间件分为远程过程调用中间件、数据访问中间件、消息中间件、事务(交易)处理中间件、分布式对象中间件。 远程过程调用...

  • nodejs19-express中间件

    中间件 匹配路由之前和之后做的操作 应用级中间件 路由级中间件 错误处理中间件 内置中间件 第三方中间件 应用级中...

  • 4.3KOA 中间件模块化与中间件合成

    中间件模块化与中间件合成 一、中间件模块化 定义中间件模块 使用中间件模块 二、使用 koa-compose 模块...

  • 4.2KOA 中间件执行流程

    中间件执行流程 代码执行流程 中间件 1 开始执行中间件 2 开始执行执行内容中间件 2 结束执行中间件 1 结束...

  • 13.中间件和上下文处理器

    中间件 中间件的引入image.png django中的中间件django 中的中间件(middleware),在...

  • Express学习

    使用中间件 Express 应用可使用如下几种中间件:* 应用级中间件* 路由级中间件* 错误处理中间...

  • Express 中间件

    中间件的概念 什么是中间件 中间件(Middleware),特指业务流程的中间处理环节。 Express 中间件的...

  • Scrapy爬虫框架(七) ------ 下载中间件(Midd

    1. Spider 下载中间件(Middleware) Spider 中间件(Middleware) 下载器中间件...

网友评论

    本文标题:中间件(六)

    本文链接:https://www.haomeiwen.com/subject/afkrmctx.html