將中間件視爲一組層,請求必須在您的應用程序中經過才能到達資源。php
例如,使用中間件,您能夠驗證用戶是否已登陸並具備足夠的權限來訪問應用程序的某些部分,不然將其重定向到其餘位置。app
實際上,中間件是控制器的擴展,由於框架的單例已經在此時構建,您可使用該ci()函數來獲取它。框架
有兩個執行點:函數
pre_controller
: 此時定義的中間件將在控制器構造函數以後執行,但在執行任何控制器操做以前執行。post_controller
: 此時定義的中間件將徹底在post_controllerCodeIgniter 的本機鉤子上運行。在某些時候您可能須要在中間件以前執行代碼,這樣作的方法是在控制器中定義一個名爲的公共方法preMiddleware:工具
<?php
# application/controllers/TestController.php
defined('BASEPATH') OR exit('No direct script access allowed');
class TestController extends CI_Controller {
public function preMiddleware() {
// This will be executed after the constructor (if it exists), but before the middleware
}
}
複製代碼
全部中間件必須保存在application/middleware文件夾中。中間件是任何帶有run()公共方法的PHP類。post
例:this
<?php
# application/middleware/TestMiddleware.php
class TestMiddleware implements Luthier\MiddlewareInterface {
public function run() {
// This is the entry point of the middleware
}
}
複製代碼
MiddlewareInterface
接口將是強制性的
Luthier\MiddlewareInterface
接口的中間件類是DEPRECATED並將在下一版本中中止工做
爲了在應用程序中分配中間件,必須同時使用類的名稱和文件的名稱。另外,請注意不要使用與框架中的其餘資源相同的名稱,例如控制器,模型,庫等。spa
luthier make middleware [name]
命令建立新的中間件
您能夠在應用程序的不一樣上下文中分配中間件:命令行
要在全局上下文中定義中間件,請使用如下語法:code
Route::middleware([name], [exec_point?]);
複製代碼
name
i中間件的名稱在哪裏, exec_point
是執行點,默認狀況下是 pre_controller
.
您可使用匿名函數而不是中間件的名稱:
Route::middleware(function(){
ci()->load->view('global_header');
});
複製代碼
在route group上下文中,中間件是另外一個屬性,所以它位於方法的第三個參數中 group()
:
Route::group('site', ['middleware' => ['AuthMiddleware']], function(){
});
複製代碼
最後,在 individual route 上下文中,中間件也是另外一個屬性,所以它在第二個參數中
Route::put('foo/bar','controller@method', ['middleware' => ['TestMiddleware']]);
複製代碼
pre_controller
要從控制器運行中間件,請使用屬性的run()
方法 middleware
:
<?php
# application/controllers/TestController.php
defined('BASEPATH') OR exit('No direct script access allowed');
class TestController extends CI_Controller {
public function __construct() {
$this->middleware->run('AuthMiddleware');
}
}
複製代碼
該屬性的 run()
方法 middleware
支持帶有中間件參數的第二個參數:
// $args can be any variable type:
$args = ['foo' => 'bar'];
$this->middleware->run('AuthMiddleware', $args);
複製代碼
只要它有一個名爲的公共方法,就能夠從外部類運行中間件 run()
<?php
# application/controllers/TestController.php
defined('BASEPATH') OR exit('No direct script access allowed');
use Vendor\CustomMiddleware;
class TestController extends CI_Controller {
public function __construct() {
$this->middleware->run(new CustomMiddleware());
}
}
複製代碼