用laavel开发一款应用程序我意识到,用Policy
可以做到的事情,完全可以用Middleware
来完成.假设我想要阻止用户在他/她不是信息所有者的情况下更新路由,我可以很容易地从路由判断,也可以从策略中执行同样的操作.
So my question is why should I use policy
over middleware and vice versa
用laavel开发一款应用程序我意识到,用Policy
可以做到的事情,完全可以用Middleware
来完成.假设我想要阻止用户在他/她不是信息所有者的情况下更新路由,我可以很容易地从路由判断,也可以从策略中执行同样的操作.
So my question is why should I use policy
over middleware and vice versa
I'm currently going through a small refactor with my roles, permissions and routes and asked myself the same question.
At the surface level, it appears true middleware and policies perform the same general idea. Check if a user can do what they are doing.
For reference here's the laravel docs...
Middleware
HTTP中间件为过滤HTTP提供了一种方便的机制
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
在我看来,中间件是关于在请求级别操作的.用"这个用户可以see个页面吗?"或者"这个用户能在这里做点什么吗?"
If so, it goes to the controller method associated with that page. Interestingly enough, Middleware may say, "Yes you may go there, but I'll write down that you are going." Etc.
一旦完成.它对用户的行为没有更多的控制权或发言权.另一方面,我认为它是中间人.
Policies
除了提供开箱即用的认证服务之外, Laravel还提供了一种简单的方法来组织授权逻辑和 控制对资源的访问.有多种方法和方法 帮助器来帮助您组织授权逻辑,并且 我们将在本文档中逐一介绍它们.
https://laravel.com/docs/master/authorization#introduction个
然而,政策似乎更关注doing人.用户可以更新任何条目,还是只更新他们的条目?
These questions seem fit for a controller method where all the calls to action on a resource are organized. Retrieve this object, store or update the article.
作为tjbb mentioned,中间件会使路由变得非常混乱和难以管理.这是我的路由文件中的一个示例:
The problem个
Route::group(['middleware' =>'role:person_type,person_type2',], function () {
Route::get('download-thing/{thing}', [
'as' => 'download-thing',
'uses' => 'ThingController@download'
]);
});
This gets very hard to read in my route file!
Another approach with policies
//ThingController
public function download(Thing $thing)
{
//Policy method and controller method match, no need to name it
$this->authorize($thing);
//download logic here....
}