laravel 中間件及路由分離


$middleware 屬性:

這個屬性稱為全局中間件,為什么說是全局中間件呢?因為你的每一次請求,這里面的每個中間件都會執行。

$routeMiddleware 屬性:

這個屬性稱為路由中間件,為什么說是路由中間件呢?因為定義在該屬性內的中間件,只能在定義路由時候引用

protected $routeMiddleware = [
    ...
    'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
];

如果我們要使用 \Illuminate\Auth\Middleware\Authenticate::class 這個中間件該怎么做呢?

Route::get('hello/laravel-china','XXController@index')->middleware('auth');

我們定義路由時候調用了 middleware 方法,參數值是 auth, 這樣訪問這個路由的時候,就會執行該中間件。明白了吧!很簡單的。

$middlewareGroups 屬性:

這個屬性稱為中間件組,為什么說是中間件組呢?我們之前說了路由中間件,是不是感覺這樣添加路由中間件很麻煩,比如我們執行 10 個中間件,是不是就要在定義路由時候添加 10 個呢?有了中間件組就不用這么麻煩了。我們來看下中間件組是怎么定義的。

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        ...
    ],
    'api' => [
        ...
    ],
];

  好了,上面的例子就是定義中間件組的格式,比如我們看 web 這個鍵值,它對應為一個數組,該數組有多個中間件組成。當我們定義好后,該怎么使用呢?
我們在聲明路由的時候,這樣調用就可以了。

Route::group(['middleware' => 'web'],function($route){
    $route->get('hello/world',function(){});
    $route->get('hello/php',function(){});
    // 這樣在訪問這個這些路由的時候,就會執行中間件組 web 所對應的中間件,方便多了,批量式的。
});

$middleware:全局中間件,要對所有的請求要做一些處理的時候,就適合定義在該屬性內。(比如統計請求次數這些)
$middlewareGroups:中間件組,比如我們項目有 api 請求和 web 的請求的時候,就要把兩種類型的請求中間件分離開來,這時候就需要我們中間件組啦。
$routeMiddleware:路由中間件,有些個別的請求,我們需要執行特別的中間件時,就適合定義在這屬性里面。

 

Laravel的路由功能很強大,默認都是定義在 routes.php 文件中,隨着項目越來越大,我們需要的定義的路由越來越多,想象一下,如果幾百上千個路由都定義在一個文件中,如何去維護?也許還有不同的人都在同一個文件定義路由,這就造成了沖突,因此我們需要分割 routes.php 文件

在 app/Providers/RouteServiceProvider.php 的 map 方法中可以如下定義:

public function map(Router $router)
{
    $router->group(['namespace' => $this->namespace], function ($router) {
        foreach (glob(app_path('Http//Routes') . '/*.php') as $file) {
            $this->app->make('App\\Http\\Routes\\' . basename($file, '.php'))->map($router);
        }
    });
}

這樣它會遍歷 app/Http/Routes/ 文件夾下的文件,遍歷每個文件路由類的 map 方法,每個文件的結構都類似,舉個例子:

<?php

namespace App\Http\Routes;

use Illuminate\Contracts\Routing\Registrar;

class HomeRoutes
{
    public function map(Registrar $router)
    {
        $router->group(['domain' => 'www.xxx.me', 'middleware' => 'web'], function ($router) {
            $router->auth();
            $router->get('/', ['as' => 'home', 'uses' => 'IndexController@index']);
            $router->get('/blog', ['as' => 'index.blog', 'uses' => 'BlogController@index']);
        });
    }
}

那么這樣路由分開多個文件后豈不是增加調用次數,會不會影響性能?答案是不必擔心。通過 Laravel 的命令:

php artisan route:cache

生成路由緩存文件后,路由只會讀取緩存文件的路由規則,因此不會影響性能,這樣做讓開發更高效和規范。

 

第二種方法

項目\app\Providers\RouteServiceProvider.php

在下方添加自己想要的

public function map()
{
    $this->mapApiRoutes();

    $this->mapWebRoutes();

    //這里隨意添加自己想要的 如后台 也可以改動他原來的代碼

     $this->mapAdminRoutes();
    
}

新增你添加的方法

protected function mapWebRoutes()
{
    Route::middleware('web')
         ->namespace($this->namespace)
         ->group(base_path('routes/web.php'));
}

   protected function mapApiRoutes()
    {
//        Route::prefix('api')
//             ->middleware('api')
//             ->namespace($this->namespace)
//             ->group(base_path('routes/api.php'));

        foreach (glob(base_path('routes/Api') . '/*.php') as $file) {
            Route::middleware('api')
                ->namespace($this->namespace)
                ->group($file);
        }

        /*        Route::prefix('api')
                     ->middleware('api')
                     ->namespace($this->namespace)
                     ->group(base_path('routes/api.php'));*/
    }

//這是新增的
protected function mapAdminRoutes()
    {
//        Route::prefix('api')
//            ->middleware('api')
//            ->namespace($this->namespace)
//            ->group(base_path('routes/api.php'));

        foreach (glob(base_path('routes/Admin') . '/*.php') as $file) {
            Route::middleware('admin')
                ->namespace($this->namespace)
                ->group($file);
        }

        /*Route::middleware('web')
             ->namespace($this->namespace)
             ->group(base_path('routes/web.php'));*/
    }

  在routes文件夾下,你就可以隨意定義自己的路由了

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM