laravel - 在所有模型中实施全局范围
问题描述
我们正在开发一个基于 Laravel Spark 的应用程序。作为其中的一部分,我们希望将资源与特定团队联系起来。
我知道我们可以添加一个全局范围,例如:
<?php
namespace App\Scopes;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
class TeamScope implements Scope
{
/**
* Apply the scope to a given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
public function apply(Builder $builder, Model $model)
{
$builder->where('team_id', '=',Auth()->user()->currentTeam->id );
}
}
但根据文档,我们必须将其添加到我们想要限制的每个模型中,如下所示:
protected static function boot()
{
parent::boot();
static::addGlobalScope(new TeamScope);
}
我的问题是可以创建未来的模型而忘记应用此代码。哪个会给我们带来安全漏洞?
有没有办法全面执行范围?
解决方案
我不确定是否有办法全局添加范围。
在我的特定应用程序中,我们不得不为我们的模型添加更多的职责。所以我们创建了一个BaseModel
扩展 Laravel 的类Illuminate\Database\Eloquent\Model
。
然后,所有新模型都扩展了BaseModel
Laravel 而不是 Laravel 的模型。
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class BaseModel extends Model
{
protected static function boot()
{
parent::boot();
static::addGlobalScope(new TeamScope);
}
}
例如:
<?php
namespace App;
class Attribute extends BaseModel
{
}
你也可以有一个特性,你可以使用它来将此范围添加到你的模型中。例如:
trait HasTeamScope
{
protected static function boot()
{
parent::boot();
static::addGlobalScope(new TeamScope);
}
}
}
...然后您可以轻松地在您的模型中重新使用它。
例如:
<?php
namespace App;
class Attribute extends BaseModel
{
use HasTeamScope;
}
现在,根据您的问题,您可能还会忘记在第一个实例中扩展 BaseModel 或在创建新模型时在第二个实例中添加 Trait。
为了解决这个问题,您可以轻松地创建一个新命令来生成将使用您自己的存根的模型(它扩展了 BaseModel 或在您创建新模型时添加特征)
推荐阅读
- python - 如何在 for 循环中使用 fillna(inplace=True)?
- autodesk-forge - 带有一些标准工具的垂直对齐工具栏
- python - 如何将glcm分类为cnn
- three.js - 为什么 3D 模型不适用于 AmbientLight?
- python - Apache Airflow:如何编写自定义传感器来检查特定条件并执行操作
- python - 从音频读取中获取光谱仪的不同背景颜色
- ffmpeg - 如何在发送一帧后立即获取数据包?
- flutter - Flutter IOS 实时文本功能
- java - 哪个层应该创建一个 HttpResponse?
- vuex - 在 vue3 组合 API 中使用来自 vuex 存储的嵌套值的正确方法