用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....
}

Laravel相关问答推荐

密码确认在Livewire中不匹配

从主类别模型 laravel 中获取子类别翻译

Laravel where 子句只返回一个数据库条目

在 laravel 中查询此类数据的最佳做法是什么?

安卓 retrofit |发布自定义对象(将 json 发送到服务器)

调用未定义函数 Illuminate\Encryption\openssl_decrypt()

Laravel 5.1 如何在Blade 文件上使用 {{ old('') }} 助手进行无线电输入

如何在使用 Laravel 在控制器中发送邮件之前更改邮件配置?

Laravel 使用 Storage::put 生成唯一 ID

如何在中间件 Laravel 中获取请求的控制器和操作的名称

删除表后如何重新迁移laravel迁移

如何利用 StorageFacade 的 Filesystem 类的 glob 方法?

laravel 4:更新行时如何从列的当前值中减一?

Laravel Socialite 在本地主机上进行测试,SSL 证书问题?

反向代理后面的 Laravel 路由

Blade 中的条件扩展

Laravel Eloquent 多态一对一?

laravel 队列 - 同步驱动程序如何工作?它是在单独的进程/线程还是主执行线程中执行?

在 Laravel 中包含 bootstrap 程序

是否可以在 Laravel 的不同数据库中引用外键?