paullhenri-l/eloquent-builder-decorator

允许您装饰 Laravel 查询构建器

2.0.0 2020-10-27 21:30 UTC

This package is auto-updated.

Last update: 2024-09-28 05:44:02 UTC


README

Build Status

此包允许您创建查询构建器装饰器。

为什么需要装饰查询构建器?

如果您正在创建一个接受查询构建器作为参数的包,并在多个地方调用相同的复杂查询,那么装饰查询构建器可能很有用。

如果您想在多个项目中共享常见查询,这也很方便。

为什么使用这个包而不是查询构建器宏系统?

虽然宏系统非常有用,但它却是全局的。

如果您的包向查询构建器添加宏,那么您的代码会对用户的代码产生副作用。

在某些情况下这可能是想要的,但如果不是,装饰是一个更安全的方法。

安装

composer require paulhenri-l/eloquent-builder-decorator

使用

创建装饰器

为了创建装饰器,您需要创建一个新的类,并使其扩展 PaulhenriL\EloquentBuilderDecorator\AbstractBuilderDecorator

在这个类中有一个 queryToDecorate 属性。这个属性包含您要装饰的构建器实例。

class QueryWithActive extends PaulhenriL\EloquentBuilderDecorator\AbstractBuilderDecorator
{
    public function whereActive()
    {
        return static::decorate(
            $this->queryToDecorate->where('active', true)
        );
    }
}

使用装饰器

现在您已经创建了装饰器,可以像这样使用它

$usersQuery = User::query();
$usersQuery = new QueryWithActive($query);

// We can now call whereActive() on the query.
$activeUsersCount = $usersQuery->whereActive()->count();

链式多个装饰器

当将装饰器串联起来时,它们变得非常强大。在这个例子中,我们将虚构的装饰器 QueryWithDates 和 QueryWithRegion 串联起来。

现在它们已经串联起来,我们的查询扩展了它们各自的方法。

我们可以按照任何顺序多次调用它们的方法。

$podcastsQuery = \DB::table('podcasts');

$podcastsQuery = new QueryWithDates($podcastsQuery);
$podcastsQuery = new QueryWithRegion($podcastsQuery);

$podcasts = $podcastsQuery->where('host', 'someone')
    ->happeningToday()
    ->inEurope()
    ->take(10)
    ->get();

注意事项

如果您想保留链式装饰器的功能,您必须确保在您的装饰器中创建的方法返回装饰器实例,而不是构建器实例。

所以您应该这样做

public function whereActive()
{
    return static::decorate(
        $this->queryToDecorate->where('active', true)
    );
}

而不应该这样做

public function whereActive()
{
    return $this->queryToDecorate->where('active', true)
}

static::decorate($query) 方法只是一个语法糖,它实际上执行的是 new static($query)

贡献

如果您对这个库的使用有任何疑问,请随时打开一个问题。

如果您认为文档或代码可以有任何改进,请打开一个PR,我会很高兴进行审查!