中間件(六)

為什么要定義中間件,定義中間件有什么好處?
1、定義一個(gè)中間件
執(zhí)行一下命令定義中間件,在我們的項(xiàng)目中就產(chǎn)生一個(gè)中間件,如下圖

php artisan make:middleware Log

在中間件中記錄請(qǐng)求的路由地址

<?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、注冊(cè)一個(gè)中間
項(xiàng)目中所有的中間件都在F:\web\learnLaravel\app\Http\Kernel.php中,我們要注冊(cè)一個(gè)中間件,只需要將我們的中間件注入即可

<?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,//我們定義的寫請(qǐng)求日志的中間件
    ];

    /**
     * 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數(shù)組當(dāng)中,我們注冊(cè)了一個(gè)中間件
3、如何使用一個(gè)中間件
修改我們的路由

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]+');
});

我們?cè)谶@個(gè)路由上添加中間件

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

訪問一下http://127.0.0.1:8000/user/1,打開我們的工程,會(huì)在日志目錄下生成一條日志,如下圖所示

image.png

4、路由分組增加中間件
調(diào)整我們的路由如下

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]+');
});

我們?cè)L問http://127.0.0.1:8000/group/prefix/user/1,就會(huì)在我們?nèi)罩局杏涗浳覀冊(cè)L問的路由地址

image.png

5、整個(gè)路由文件增加中間件
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'));
    }
}

我們?cè)趍apWebRoutes方法中,引入了中間件
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]+');
});

那么我們?cè)L問web下面任何一個(gè)路由地址都會(huì)產(chǎn)生一條日志

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 官網(wǎng) 中文版本 好的網(wǎng)站 Content-type: text/htmlBASH Section: User ...
    不排版閱讀 4,716評(píng)論 0 5
  • 一、Python簡介和環(huán)境搭建以及pip的安裝 4課時(shí)實(shí)驗(yàn)課主要內(nèi)容 【Python簡介】: Python 是一個(gè)...
    _小老虎_閱讀 6,338評(píng)論 0 10
  • 紅豆生南國, 春來發(fā)枝冬凋敝, 相思不如不相思。
    何必放縱閱讀 508評(píng)論 0 1
  • 昨天,通過咨詢,和醫(yī)生溝通,我和先生說不想做鼻甲肥大,和鼻中隔偏曲這兩樣手術(shù),只做鼻黏連分離術(shù),她說尊重我的選擇。...
    素心若雪_b5b4閱讀 219評(píng)論 0 0
  • 看破紅塵天地寬。名不貪婪,利不貪婪。真誠清凈悟真禪,平等慈悲,普度人間。 歷盡劫波始豁然。佛法無邊,向上心歡。念佛...
    勝者為王王臣森閱讀 497評(píng)論 0 0

友情鏈接更多精彩內(nèi)容