本文实例讲述了Laravel框架控制器的middleware中间件用法。分享给大家供大家参考,具体如下:
场景:活动开始前只能访问宣传页面,开始后才可以访问其他页面:
步骤:
新建中间件,
注册中间件,
使用中间件,
中间件的前置和后置操作。
控制器:
1
2
3
4
5
6
7
8
9
|
public function activity0(){
return '活动快要开始啦,敬请期待' ;
}
public function activity1(){
return '活动页面1' ;
}
public function activity2(){
return '活动页面2' ;
}
|
路由:
1
2
3
|
Route::any( 'activity0' ,[ 'uses' => 'StudentController@activity0' ]);
Route::any( 'activity1' ,[ 'uses' => 'StudentController@activity1' ]);
Route::any( 'activity2' ,[ 'uses' => 'StudentController@activity2' ]);
|
在App\Http\Middleware下创建中间件Activity.php:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
namespace App\Http\Middleware;
use Closure;
class Activity{
public function handle( $request ,Closure $next ){
if (time() < strtotime ( '2018-01-01' )){
return redirect( 'activity0' );
}
return $next ( $request );
}
}
//注册中间件,在Kernel.php中的$routeMiddleware数组中增加
protected $routeMiddleware = [
'activity' => \App\Http\Middleware\Activity:: class ,
];
|
使用中间件,路由中的设置
1
2
3
4
5
6
|
//宣传页面不需要中间件验证,不能放里边
Route::any( 'activity0' ,[ 'uses' => 'StudentController@activity0' ]);
Route::group([ 'middleware' =>[ 'activity' ]], function (){
Route::any( 'activity1' ,[ 'uses' => 'StudentController@activity1' ]);
Route::any( 'activity2' ,[ 'uses' => 'StudentController@activity2' ]);
});
|
1
2
3
4
5
6
|
//后置中间件
public function handle( $request ,Closure $next ){
$response = $next ( $request );
echo $response ;
echo '我是后置操作' ;
}
|
希望本文所述对大家基于Laravel框架的PHP程序设计有所帮助。
原文链接:https://www.cnblogs.com/gyfluck/p/9041407.html