gpt4 book ai didi

php - Laravel:路由中间件和策略之间的区别

转载 作者:IT王子 更新时间:2023-10-28 23:55:04 26 4
gpt4 key购买 nike

使用 laravel 开发应用程序我意识到使用 Policy 可以完成的事情完全可以使用 Middleware 完成。假设我想阻止用户更新路由,如果他/她不是信息的所有者,我可以轻松地从路由中检查并且可以从策略中执行相同的操作。

所以我的问题是为什么我应该使用 policy 而不是中间件,反之亦然

最佳答案

我目前正在对我的角色、权限和路由进行小型重构,并问自己同样的问题。

从表面上看,真正的中间件和策略似乎执行相同的总体思想。检查用户是否可以做他们正在做的事情。

引用这里的 laravel 文档...

中间件“我可以看看这个吗?我可以去这里吗?”

HTTP middleware provide a convenient mechanism for filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.

Of course, additional middleware can be written to perform a variety of tasks besides authentication. A CORS middleware might be responsible for adding the proper headers to all responses leaving your application. A logging middleware might log all incoming requests to your application.

https://laravel.com/docs/master/middleware#introduction

在我的阅读中,中间件是关于在请求级别运行的。在“这个用户可以看到一个页面吗?”或者“这个用户可以在这里做点什么吗?”的术语中。

如果是这样,它会转到与该页面关联的 Controller 方法。有趣的是,中间件可能会说,“是的,你可以去那里,但我会写下你要去的地方。”等等

一旦完成。它对用户正在做什么没有更多的控制权或发言权。我将其视为中间人的另一种方式。

政策“我可以这样做吗?我可以改变这个吗?”

In addition to providing authentication services out of the box, Laravel also provides a simple way to organize authorization logic and control access to resources. There are a variety of methods and helpers to assist you in organizing your authorization logic, and we'll cover each of them in this document.

https://laravel.com/docs/master/authorization#introduction

然而,政策似乎更关注。用户可以更新任何条目,还是只能更新他们的条目?

这些问题似乎适合 Controller 方法,在该方法中组织了对资源的所有操作调用。检索此对象、存储或更新文章。

作为tjbb mentioned ,中间件会使路由变得非常困惑且难以管理。这是我的路线文件中的示例:

问题

    Route::group(['middleware' =>'role:person_type,person_type2',], function () {
Route::get('download-thing/{thing}', [
'as' => 'download-thing',
'uses' => 'ThingController@download'
]);
});

这在我的路线文件中很难阅读!

另一种策略方法

//ThingController
public function download(Thing $thing)
{
//Policy method and controller method match, no need to name it
$this->authorize($thing);

//download logic here....
}

关于php - Laravel:路由中间件和策略之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35019292/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com