Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:用了框架,就要遵循框架的规范与注册流程, 这些让步要做的
作业:创建一个路由中间件,并通过访问url地址来触发中间件输出一名话:‘hello middware’
先新建一个中间件,这里采用命令行创建,执行如下代码:
php artisan make:middleware Check
运行后如下图所示:
Check.php代码如下所示:
<?php namespace App\Http\Middleware; use Closure; class Check { //注意这里必需是handle public function handle($req,Closure $next){ $username='admin'; if($username != 'admin'){ exit('没有权限操作'); } echo 'Hello Middleware!'; return $next($req); } }
紧接着注册中间件(必需的步骤),在kernel.php这个文件添加代码:
找到这一块的代码,新增最后一行,注册中间件:
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, 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, 'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class, //在这里添加后面的代码 'check' => \App\Http\Middleware\Check::class ];
新建控制器文件Home.php:
<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use Illuminate\Http\Request; class Home extends Controller { public function index(Request $req){ } }
最后添加路由的代码,在web.php文件里面:
Route::get('/Home','Home@index')->middleware('check'); //这里的check就是在注册路由的时候的Key值
运行后效果如下图所示:
注意使用中间件的时候一定要注册,还有中间件方法名称必需为handle