gpt4 book ai didi

php - 优雅地退出 Laravel 作用域

转载 作者:行者123 更新时间:2023-12-04 09:25:54 26 4
gpt4 key购买 nike

我有一个范围,它根据用户角色以一种限制方式起作用,您可以将一组规则转发到限制数据库最终输出的范围。
一个真正简化的角色限制示例:

{
"first_name": "=foo%"
}
只会返回 first_name 的记录以 foo% 开头,这实际上意味着我已禁止具有该角色的用户查看任何不以 foo% 开头的记录。 .
这种方法的问题在于,如果某人没有施加任何限制,他将看到一切。我知道这是一个有效的假设,但如果没有施加限制,我想禁止一切,这样如果创建新角色,它就没有任何权利。
目前我正在为这种情况抛出异常:
public function apply(Builder $builder, Model $model)
{
$input = $this->getAuthValues(get_class($model));

if (count($input) < 1) {
throw new \Exception('No rights for you');
}

$jsonQuery = new JsonQuery($builder, $input); <-- class responsible for assembling the queries based on the input
$jsonQuery->search();
}
但这当然也不异常(exception)。在这种情况下,我希望返回空数组。
我可以使用某种方法优雅地退出范围以及一个空结果,而不实际执行查询吗?

最佳答案

由于范围通常是链接的(流畅地调用),并且范围不直接负责执行查询,我认为您不能“优雅地退出”,因为下一次调用仍将期待 Builder工作的对象。
一种可能的解决方案(不简单)是创建一个扩展 Builder 的类。类,并覆盖所有负责从数据库中实际获取结果的方法。我不确定您需要覆盖的所有方法才能使其在所有情况下都能正常工作。您可能还想处理 AbortedBuilder 中的一些插入和更新情况。以及。

class AbortedBuilder extends Builder
{
...

/**
* Run the query as a "select" statement against the connection.
*
* @return array
*/
protected function runSelect()
{
return [];
}

...

/**
* Run a pagination count query.
*
* @param array $columns
* @return array
*/
protected function runPaginationCountQuery($columns = ['*'])
{
return [];
}

...

/**
* Insert a new record and get the value of the primary key.
*
* @param array $values
* @param string|null $sequence
* @return int
*/
public function insertGetId(array $values, $sequence = null)
{
throw new \Exception('You are trying to insert using an aborted query!');
}

...
}
然后在您的范围内,您可以执行以下操作:
public function apply(Builder $builder, Model $model)
{
$input = $this->getAuthValues(get_class($model));

if (count($input) < 1) {
$builder = new AbortedBuilder();
} else {
$jsonQuery = new JsonQuery($builder, $input);
$jsonQuery->search();
}

关于php - 优雅地退出 Laravel 作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63010974/

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