• Laravel Middleware 中间件笔记


    Laravel的中间件可以方便的过滤进入我们网页的请求。包括用户授权,CORS来指定流出请求的header等。

    定义一个新的中间件可以使用命令:

    php artisan make:middleware AgeMiddleware

    这条命令在app/Http/Middleware中创建AgeMiddleware类。

    我们假设我们过滤所有年龄小于200的请求:

    <?php
    
    namespace AppHttpMiddleware;
    
    use Closure;
    
    class AgeMiddleware
    {
        /**
         * Run the request filter.
         *
         * @param  IlluminateHttpRequest  $request
         * @param  Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
            if ($request->input('age') <= 200) {
                return redirect('home');
            }
    
            return $next($request);
        }
    
    }

    通过调用$next回调函数就可以将请求往下传递。

    Middleware的过滤不局限于请求到达,当请求处理完毕后,也可以经由Middleware处理过滤:

    <?php
    
    namespace AppHttpMiddleware;
    
    use Closure;
    
    class BeforeMiddleware
    {
        public function handle($request, Closure $next)
        {
            // Perform action
    
            return $next($request);
        }
    }
    
    <?php
    
    namespace AppHttpMiddleware;
    
    use Closure;
    
    class AfterMiddleware
    {
        public function handle($request, Closure $next)
        {
            $response = $next($request);
    
            // Perform action
    
            return $response;
        }
    }

    如果需要你的middleware能够过滤全部Http请求,只需要在app/Http/Kernel.php的$middleware中列出即可。

    如果需要将middleware指定给特定的route,首先需要在app/Http/Kernel.php中的$routeMiddleware里声明一个简单的key:

    protected $routeMiddleware = [
        'auth' => AppHttpMiddlewareAuthenticate::class,
        'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
        'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
        'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
    ];

    声明后即可在route里使用,route还可以同时指定多个middleware:

    Route::get('admin/profile', ['middleware' => 'auth', function () {
        //
    }]);
    
    Route::get('/', ['middleware' => ['first', 'second'], function () {
        //
    }]);

    也可以通过方法指定:

    Route::get('/', function () {
        //
    })->middleware(['first', 'second']);

    我们也可以将多个Middleware Group在app/Http/Kernel.php中声明成为一个Middleware,如我们熟知的web和api Middleware:

    protected $middlewareGroups = [
        'web' => [
            AppHttpMiddlewareEncryptCookies::class,
            IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
            IlluminateSessionMiddlewareStartSession::class,
            IlluminateViewMiddlewareShareErrorsFromSession::class,
            AppHttpMiddlewareVerifyCsrfToken::class,
        ],
    
        'api' => [
            'throttle:60,1',
            'auth:api',
        ],
    ];

    Middleware同时也接受传参,只需要在最后一个变量$next后加入新的参数即可。传参时需要在route中用:分隔Middleware和参数:

    <?php
    
    namespace AppHttpMiddleware;
    
    use Closure;
    
    class RoleMiddleware
    {
        /**
         * Run the request filter.
         *
         * @param  IlluminateHttpRequest  $request
         * @param  Closure  $next
         * @param  string  $role
         * @return mixed
         */
        public function handle($request, Closure $next, $role)
        {
            if (! $request->user()->hasRole($role)) {
                // Redirect...
            }
    
            return $next($request);
        }
    
    }
    
    Route::put('post/{id}', ['middleware' => 'role:editor', function ($id) {
        //
    }]);
  • 相关阅读:
    Java的一天学习
    IIS7配置PHP图解
    主流HTML5游戏框架的分析和对比
    HTTP请求
    hibernate -- 数据库连接池的失效检查设置
    mysql备份
    深入探索SOAP1.1--使用SAAJ1.2.1
    JDBC连接执行MySQL存储过程报权限错误
    mysql(connector/ODBC)
    mysql查询优化(三)
  • 原文地址:https://www.cnblogs.com/xiaoxiaff/p/5272298.html
Copyright © 2020-2023  润新知