当前位置: 首页 > 后端技术 > PHP

Laravel策略使用

时间:2023-03-29 19:26:24 PHP

Laravel提供了一种更简单的方法来处理用户授权操作。与用户认证类似,实现用户授权主要有两种方式:门和策略。这里我主要讲解策略的使用。文档里面有详细的说明,我只是根据自己的使用过程做一个简单的说明。例子:我准备使用编辑文章的权限来演示。在此权限下,只有文章的所有者可以编辑。下面我们来体验一下Policy是如何实现的。准备工作安装laravelcomposercreate-project--prefer-distlaravel/laravellaravel-vue"5.5.*"buildtablephpartisanmake:migrationposts--create=postsSchema::create('posts',function(Blueprint$table){$table->increments('id');$table->string("title",200);$table->text("content");$table->timestamps();$table->index('用户身份');});创建模型phpartisanmake:modelPostModel#app/PostModel.phpnamespaceApp\Models;useIlluminate\Database\Eloquent\Model;classPostModelextendsModel{protected$table='posts';protected$fillable=['title','content','user_id'];}生成policypolicy其实就是授权方案对应的class文件,在app/Policies目录下。接下来,我使用命令创建策略文件。执行phpartisanmake:policyPostPolicy命令后,会生成app/Policies/PostPolicy.php文件。让我们开始编辑吧。#app/Policies/PostPolicy.phpnamespaceApp\Policies;useApp\User;useApp\PostModel;useIlluminate\Auth\Access\HandlesAuthorization;classTopicPolicy{使用HandlesAuthorization;publicfunctioncreate(User$user){//代码}publicfunctionupdate(User$user,PostModel$postModel){return$user->id===$postModel->user_id;}publicfunctiondelete(User$user,PostModel$postModel){//代码}}注册策略授权策略需要注册后才能使用。在哪里可以注册?laravel5.5在AuthServiceProvider中包含一个policies属性,用于注册策略。让我们看看如何注册。#app/Providers/AuthServiceProvider.phpnamespaceApp\Providers;useIlluminate\Support\Facades\Gate;useIlluminate\Foundation\Support\Providers\AuthServiceProvider作为ServiceProvider;userApp\PostModel;useApp\Policies\PostPolicy;classAuthServiceProviderextendsServiceProvider{protected$policies=[PostModel::class=>PostPolicy::class,//注意策略是在这里注册的];publicfunctionboot(){$this->registerPolicies();}}使用policy注册后,在User模型中有can和cant方法使用策略,比如在编辑PostController时:#app/Http/Controllers/PostController.phppublicfunctioncreate(){if(Auth::user()->can('create',PostModel)){//注意这里的用法//可以创建}else{//没有权限}}publicfunctionupdate(Request$request){$id=$request->输入('ID');$post=PostModel::findOrFail($id);if(Auth::user()->can('update',$post)){//可以编辑}else{//没有编辑权限}}如果想让超级管理员也有编辑权限,可以添加定义策略时的策略过滤器,它是一个before方法:#app/Policies/PostPolicy.phppublicfunctionbefore($user,$ability){if($user->isSuperAdmin()){返回真;}}#app/User.phppublicfunctionisSuperAdmin(){//定义ID为1为超级管理员if($this->id==1){returntrue;}returnfalse;}使用balde模板中的@can和@cannot方法判断@can('create',App\PostModel::class)Create@endcan@can("update",$post)编辑@endcan好了,这次就写到这里了,希望这篇笔记可以帮助大家解决