博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
laravel 中间件_了解Laravel中间件
阅读量:2511 次
发布时间:2019-05-11

本文共 7300 字,大约阅读时间需要 24 分钟。

laravel 中间件

HTTP Middlewares provide a convenient mechanism for filtering HTTP requests entering your application. Laravel, for example, has a middleware for verifying a user's authentication.

HTTP中间件为过滤进入您的应用程序的HTTP请求提供了一种方便的机制。 例如,Laravel具有用于验证用户身份验证的中间件。

( )

These are some cases where I have had to resort to using middleware. There are many more cases where you would like to use a middleware.

在某些情况下,我不得不诉诸于使用中间件。 在许多情况下,您想使用中间件。

  • Using a middleware to confirm the incoming route request API key. Assuming you are building an API.

    使用中间件确认传入的路由请求API密钥。 假设您正在构建一个API。
  • Rate-limiting a service call.

    限制服务呼叫的速率。
  • Change the site language based on locale.

    根据语言环境更改网站语言。
  • Enable site-wide maintenance.

    启用站点范围的维护。
  • Sniffing bot traffic.

    嗅探机器人流量。
  • Logging.

    正在记录。

By the end of this article, you should be able to create a middleware, registers it and use it in your projects. We will be illustrating the creation till usage of middlewares by creating one of our own. Our middleware will enable maintenance either site-wide or on some routes.

到本文结尾,您应该能够创建一个中间件,进行注册并在项目中使用它。 我们将通过创建我们自己的一个演示在中间件使用之前的创建过程。 我们的中间件可以在站点范围内或某些路由上进行维护。

( )

Thanks to artisan, creating middlewares in Laravel is easy. All we need do is open a terminal in the project root and run the following command.

感谢artisan ,在Laravel中创建中间件非常容易。 我们需要做的就是在项目根目录中打开一个终端,然后运行以下命令。

// Replace 
with the actual name of the middleware.php artisan make:middleware

This command creates our middleware class in app/Http/Middleware. To create our own middleware (which we will call DownForMaintenance, we can.

此命令在app/Http/Middleware创建我们的中间件类。 创建我们自己的中间件(我们将其称为DownForMaintenance )。

php artisan make:middleware DownForMaintenance

So we can now open our middleware class and add our logic to the middleware. Remember, our middleware handles site maintenance mode. We need to first import the HttpException first. At the top of the file, we can do this

因此,我们现在可以打开中间件类并将逻辑添加到中间件。 请记住,我们的中间件处理站点维护模式。 我们需要先导入HttpException 。 在文件的顶部,我们可以执行此操作

use Symfony\Component\HttpKernel\Exception\HttpException;

In the handle method of our middleware, we can just do this.

在我们的中间件的handle方法中,我们可以做到这一点。

public function handle($request, Closure $next){
throw new HttpException(503);}

By throwing this exception, Laravel knows to load the 503.blade.php file. This should contain the message for maintenance mode.

通过抛出此异常,Laravel知道要加载503.blade.php文件。 它应该包含维护模式的消息。

( )

Now that we've created a middleware, we need to let the application know the middleware exists. If you want a middleware to run on every request, go to app/Http/kernel.php and add the middleware FQN to Kernel class $middleware property.

现在我们已经创建了中间件,我们需要让应用程序知道中间件的存在。 如果要在每个请求上运行中间件,请转到app/Http/kernel.php并将中间件FQN添加到Kernel$middleware属性。

protected $middleware = [    ...    \App\Http\Middleware\DownForMaintenance::class];

By doing this, the user will see a message for every page they visit.

这样,用户将在访问的每个页面上看到一条消息。

If you want the middleware to trigger on some routes, we can name the middleware and use that as a reference mechanism to add it to some routes. To name the middleware, while still in the app/Http/kernel.php, add the keyed property to the $routeMiddleware array. The array key is the name of the middleware, while the value should be the FQN of the middleware.

如果您希望中间件在某些路由上触发,我们可以命名中间件并将其用作将其添加到某些路由的参考机制。 要命名中间件,尽管仍在app/Http/kernel.php ,但将其keyed属性添加到$routeMiddleware数组中。 数组键是中间件的名称,而值应该是中间件的FQN。

protected $routeMiddleware = [    ...    'down.for.maintenance' => \App\Http\Middleware\DownForMaintenance::class,    ...];

( )

Take this route for example,

以这条路线为例,

Route::get('posts/{something}', 'PostController@getPost');

the getPost method on the PostController class fires when the url matches posts/{something}.

网址匹配posts/{something}时,将触发PostController类上的getPost方法。

We could add our down.for.maintenance middleware by changing the second parameter of Route::get to an array which contains a middleware property and closure which processes the route.

我们可以通过将Route::get的第二个参数更改为包含中间件属性和处理路由的闭包的数组来添加我们的down.for.maintenance中间件。

Route::get('posts/{something}', ['middleware' => 'grown.ups.only', function () {
return "Only big boys/girls can see this.";}]);

By doing this, only routes matching posts/{something} will show the down for maintenance error.

这样,只有匹配posts/{something}路线才会显示停机维护错误。

Another to add middleware to routes is to call a middleware method on the route definition. Like this.

向路由添加中间件的另一个方法是在路由定义上调用middleware方法。 像这样。

Route::get('posts/{something}', function () {
//})->middleware(['first', 'second']);

( )

Passing parameters to middlewares is quite easy. Say, for example, our middleware validates the role of a user before allowing access to a page. We could also pass a list of allowed roles to the middleware.

将参数传递给中间件非常容易。 举例来说,我们的中间件在允许访问页面之前先验证用户的角色。 我们还可以将允许的角色列表传递给中间件。

To pass a parameter to our middleware, after the $request and Closure parameters, we then add our variables.

为了将参数传递给中间件,在$requestClosure参数之后,我们然后添加变量。

public function handle($request, Closure $next, $role){
if (! $request->user()->hasRole($role)) {
// Redirect... } return $next($request);}

To pass the variable, when attaching our middleware to routes, we do this.

为了传递变量,在将我们的中间件附加到路由时,我们执行此操作。

Route::put('post/{id}', ['middleware' => 'role:editor', function ($id) {
//}]);

( )

At times, there might be a bunch of middlewares you apply to a couple of routes. It would be better if we could combine or group middlewares. This allows us to reuse that group of middlewares.

有时,您可能会在许多路由中应用大量中间件。 如果我们可以组合或组合中间件,那会更好。 这使我们可以重用那组中间件。

To group middlewares, we add a $middlewareGroups property (if it does not exist) to the Kernel class. This property takes a key-value pair array. The key represents the group name, and the value is an array of middleware FQNs. By default, Laravel provides a web, and api group.

为了对中间件进行分组,我们向Kernel类添加了$middlewareGroups属性(如果不存在)。 此属性采用键值对数组。 键代表组名,值是中间件FQN的数组。 默认情况下,Laravel提供了一个webapi组。

protected $middlewareGroups = [    'web' => [        \App\Http\Middleware\EncryptCookies::class,        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,        \Illuminate\Session\Middleware\StartSession::class,        \Illuminate\View\Middleware\ShareErrorsFromSession::class,        \App\Http\Middleware\VerifyCsrfToken::class,    ],    'api' => [        'throttle:60,1',        'auth:api',    ],];

If we need to use this group in our application, we can then do this.

如果需要在应用程序中使用此组,则可以执行此操作。

Route::group(['middleware' => ['web']], function () {
//});

( )

If you noticed, throughout this article we perform an action then execute our middleware. But we could also execute our middleware first before returning a response.

如果您注意到了,在本文中我们将执行一个操作,然后执行我们的中间件。 但是我们也可以在返回响应之前先执行中间件。

public function handle($request, Closure $next){
$response = $next($request); /** * Perform actions here */ return $response;}

By doing this, we first execute our middleware then we perform our action and return the response.

通过这样做,我们首先执行中间件,然后执行操作并返回响应。

( )

The use-cases mentioned above are just some few examples. You can create a middleware to do so much more than what I have listed above.

上面提到的用例只是一些示例。 您可以创建一个中间件,以完成比上面列出的更多的工作。

翻译自:

laravel 中间件

转载地址:http://eguwd.baihongyu.com/

你可能感兴趣的文章
TestNG(五)常用元素的操作
查看>>
解决 Visual Studio 点击添加引用无反应的问题
查看>>
通过镜像下载Android系统源码
查看>>
python字符串格式化 %操作符 {}操作符---总结
查看>>
windows 不能在 本地计算机 启动 Apache
查看>>
iOS开发报duplicate symbols for architecture x86_64错误的问题
查看>>
Chap-6 6.4.2 堆和栈
查看>>
【Java学习笔记之九】java二维数组及其多维数组的内存应用拓展延伸
查看>>
C# MySql 连接
查看>>
网络抓包分析方法大全
查看>>
sql 数据类型
查看>>
android 截图
查看>>
WebServicer接口类生成方法。
查看>>
POJ 1740
查看>>
【翻译】火影忍者鸣人 疾风传 终级风暴2 制作介绍
查看>>
http和webservice
查看>>
hdu1879------------prim算法模板
查看>>
jdbc之二:DAO模式
查看>>
MySQL性能优化方法一:缓存参数优化
查看>>
Angular2 - 概述
查看>>