梦入琼楼寒有月,行过石树冻无烟

Laravel 中间件

在Laravel之中,中间件提供了一种较为方便的机制来过滤应用程序的HTTP请求,如果学习过Spring security的读者肯定不陌生,假如Larvael有一个认证身份的中间件,如果未经过授权就可以访问不可访问的内容,则会被重定向至登录界面。
在Laravel之中不仅仅包含了身分验证的中间件,还自带了CSRF防护的中间件,而中间件所在的目录即在/app/Http/Middleware目录下,所以我们需要定义一个中间件:

php artisan make:middleware MiddleWare

在这里之中作者出现了一个潜规则的错误,在创建中间件的过程中应该使用 需求+中间件的潜规则,则按照潜规则来命名的话需要这样:IdMiddleware

之后我们会发现他Laravel会在app/Http/Middleware目录下创建一个MiddleWare.php类,在这个中间件中我们可以对其进行写入:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php

namespace App\Http\Middleware;

use Closure;

class MiddleWare
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
echo "Is be Middleware";
return $next($request);

}
}

在中间件中,我们所定义了一个当当前id等于10的情况下,将会返回一个yes

注册中间件


在此之后我们需要去注册一个全局的中间件。全局中间件需要在app/Http/Kernel.php中进行。

全局注册

1
2
3
4
5
6
7
8
9
10
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
……
\App\Http\Middleware\MiddleWare::class,
],

全局注册即所有路由都将经过的中间件,我们可以在$middlewareGroups下进行添加之后访问localhost:8000即可查看中间件所输出的Hello,world!。

路由注册

1
2
3
4
5
6
7
8
9
10
11
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
……
'hey' => \App\Http\Middleware\MiddleWare::class,
];

在Kernel类中,我们注册了一个MiddleWare名为的中间件,其注册语法为:'id' => \App\Http\Middleware\MiddleWare::class,

控制器

路由注册长伴着控制器一起进行,通常在Laravel项目中控制器并不是默认存在的,需要使用如下命令进行生成:

php artisan make:controller TestController

之后Controller控制器将会存放在App\Http\Controllers目录下,并存在着一个TestController的类。

TestController
1
2
3
4
5
6
7
8
9
10
11
12
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TestController extends Controller
{
public function index() {
echo "<br>Is be Controller";
}
}

web.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
return view('welcome');
});

// 使用路由器组进行绑定
Route::group(['middleware' => ['hey']], function () {
Route::get('test','TestController@index')->name('test');
});
⬅️ Go back