Blogger Information
Blog 26
fans 1
comment 2
visits 21640
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
11月8日:创建一个路由中间件,并通过访问url地址来触发中间件输出一名话:‘hello middware’练习作业
星空的博客
Original
1039 people have browsed it

创建中间件->laravel文件目录里的Middleware目录里手动创建一个名为:ChekAge.php 的中间件文档。

 也可以使用命令创建:php artisan make:middleware CheckAge  如下截图!

实例

<?php
	namespace App\Http\Middleware;

	use Closure; //闭包类型

	/**
	 * 
	 */
	class CheckAge 

	{

		//创建一个方法 handle 固定这个名称
		//$req 表示当前请求
		//型参$next里声明 闭包类型

		public function handle($req,Closure $next){

			echo 'hello hello middware';

		     return	$next($req); //返回这个请求

		}
		
	}

运行实例 »

点击 "运行实例" 按钮查看在线实例

image.png

注册中间件->打开laravel文件目录里的Middleware目录的Kernel.php(下图一);打开找到 protected $routeMiddleware=[];创建注册:(下图二)(这里就是放中间件的目录)


image.png

实例

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \App\Http\Middleware\TrustProxies::class,
        \App\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    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,
        //自定义中间件
        'checkage'=>\App\Http\Middleware\CheckAge::class,
        
    ];

    /**
     * The priority-sorted list of middleware.
     *
     * This forces non-global middleware to always be in the given order.
     *
     * @var array
     */
    protected $middlewarePriority = [
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\Authenticate::class,
        \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \Illuminate\Auth\Middleware\Authorize::class,
    ];
}

运行实例 »

点击 "运行实例" 按钮查看在线实例

image.png

三 、执行中间件->,到laravel目录下的routes文件夹中打开web.php路由文件文件创建执行中间件把在注册的中间件名称输出到要执行的名称里。

实例

<?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 () {
	echo 'hello world'; return;
    return view('welcome');
});


Route::get('/304525', function () {
	
	// $article=array('title'=>'2019年国庆大阅兵','detail'=>'全景过程,4K超高清再现!','auth'=>array('admin',18));

 $data =array('articles' =>array(

		0=>array('title'=>'2019年国庆大阅兵'),
		1=>array('title'=>'2019年1111看点'),
		2=>array('title'=>'2019台湾收复回来了')
	));

    return view('article/detail',$data);
});


Route::get('/admin/home/index','admin\Home@index');
Route::get('/dbtest/index','dbtest@index');
Route::get('/dbtest/models','dbtest@models');

// Route::get('/account/login','Account@login')->name('qtdl'); 


Route::get('/home','Home@index')->middleware('checkage');

//1.解析/home
//2.$home =new Home()

//3.调用$home->index();

运行实例 »

点击 "运行实例" 按钮查看在线实例

image.png

四,在地址输入路由http://wf/home 打开文件查看中间件效果

实例

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

class Home extends Controller
{
	//Request $req 接收这个请求
   public function index(Request $req){

   	// return redirect()->route('qtdl');
   	echo '这是公司核心数据,只有管理员才能查看';
   	
   }
}

运行实例 »

点击 "运行实例" 按钮查看在线实例

image.png


Correction status:qualified

Teacher's comments:中间件的功能非常强大, 不仅仅是请求拦截器, 还可以完成很多的
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post