屎山警告!Pipeline竟优雅的处理了Laravel多条件查询

原标题:Laravel Eloquent Query Filter using Pipeline
原文链接:hafiqiqmal93.medium.com/laravel-el...

pipeline是Laravel 特别有用的特性之一。 pipeline也是 Laravel 中最常用的组件之一,例如中间件。

One of the features of Laravel which surely useful is the pipeline. Pipelines is one of the most used components in the Laravel for example middleware.

基本上,通过管道,我们可以通过任务堆栈传递对象,并通过回调获得结果。

Basically, with a pipeline we can pass an object through a stack of tasks and get the result via a callback.

管道用于查询过滤的好处是我们可以将成吨的屎山减少到几行。 没用管道之前,我们通常会写一个控制器,获取用户模型的 Eloquent 实例,并根据查询字符串拼接一些条件。

The benefit of pipeline for query filtering is that we can reduce tons of lines to several lines. Being unaware of the pipelines, we would usually set up a controller, get an instance of Eloquent of User model, and apply some condition based on query string.

让我们看看下面的屎山查询大法。

Let’s see below queries.

$query = User::query();
if ($request->username) {
    $query->where('username', 'LIKE', "%$request->username%");
}
if ($request->email) {
    $query->where('email', 'LIKE', "%$request->email%");
}
if ($request->address) {
    $query->where('address', 'LIKE', "%$request->address%");
}
if ($request->occupation) {
    $query->where('occupation', 'LIKE', "%$request->occupation%");
}
return $query->get();

缺点很明显,过滤条件像屎山一样不断的堆加,出现大量重复的代码。 另外,代码的可维护性就有点脑壳疼了。

The drawback is that, it’s obviously that filters conditions will continue to grow as well as duplication of the same filter for other query. In other hand, the maintainability of the code kind of headache.

来看看管道优雅的处理方式
There is where Pipeline become a hero 😎

return User::query()->filter([ 
    UsernameFilter::class,
    EmailFilter::class,
    AddressFilter::class,
    OccupationFilter::class
])->get();

简单而简短吧?看看下面的步骤

Simple and short right? But before that,

1. 创建一个名为“Filterable”的trait类并写一个scope方法

  1. Create a trait named Filterable and create a scope
class Filterable
{ 
       public function scopeFilter($query, array $through)
       {        
            return app(Pipeline::class)
                   ->send($query)            
                   ->through($through)            
                   ->thenReturn();    
       }
}

然后,你就可以愉快的在任意Model中复用它,如User模型

Then, use it in any model that you prefer, for example User model

class User 
{
    use Filterable; 
}

2.创建一个Filter,例如UsernameFilter

2. Create a filter for example UsernameFilter

class UsernameFilter 
{
    public function handle($query, $next)
    {        
        if (request()->mobile_phone) {           
           $query->where('username', request()->mobile_phone);      
        }         
        return $next($query);  
    }
}

食用方法:

The usage is just like this

User::query()->filter([UsernameFilter::class])->get();

或者

OR

你还可以通过传递属性的方式来使用管道。

If you want for more accessibility to the pipeline, you can also pass an attribute.

class StringFilter 
{
    public function handle($query, $next, $column) {
        if (request()->{$column}) {           
            $query->where($column, 'LIKE', request()->{$column});      
        } 
        return $next($query); 
    }
}

像下面这样用

The usage is just like this

User::query()->filter([
   'StringFilter:username',
   'StringFilter:email',
])->get();

搞定,优雅吧!😎

Done. Simple and clean 😎

For your references:
hafiqiqmal93.medium.com/laravel-el...
www.hackdoor.io/articles/discoveri...
gist.github.com/afiqiqmal/ef19a4ea...

CV专员在静静的抄你码
本帖已被设为精华帖!
本帖由系统于 2年前 自动加精
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
讨论数量: 35

不懂就问,为何不这样

$query = User::query();
foreach(['username', 'email'] as $where)
    if ($request->{$where}) {
        $query->where($where, 'LIKE', "%$request->{$where}%");
    }
}

return $query->get();
2年前 评论
徵羽宫 10个月前

php就是这样没落的麽?不考虑一些实用性的东西,净整些屎一样封装,跟古代的那些读书人很像。文绉绉的,没点屁用。

2年前 评论
徵羽宫 10个月前
徵羽宫 10个月前

不懂就问,为何不这样

$query = User::query();
foreach(['username', 'email'] as $where)
    if ($request->{$where}) {
        $query->where($where, 'LIKE', "%$request->{$where}%");
    }
}

return $query->get();
2年前 评论
徵羽宫 10个月前

php就是这样没落的麽?不考虑一些实用性的东西,净整些屎一样封装,跟古代的那些读书人很像。文绉绉的,没点屁用。

2年前 评论
徵羽宫 10个月前
徵羽宫 10个月前

为了封装而封装?

2年前 评论

可以试试 : tucker-eric/eloquentfilter

2年前 评论

我基本不用if,都是使用when,这个比when有性能的提升吗?

2年前 评论

我还是觉得第一种好 可能我的比较 :hankey:

2年前 评论

方法是好的, 但是这个场景并不合适你这样做

你这个场景还是用 if else 吧, 简单易懂, 维护成本低, 换个人一眼也看出来了, 或者用

tucker-eric/eloquentfilter

这个扩展包

2年前 评论

感觉这也太麻烦了。。。

2年前 评论

pipeline 适用于流程控制,也就是像金融贷款一样的业务,很多很多控制,但是不同业务场景可能需要的流程不一样的话,可以使用 pipline 来组合控制,而且可以调顺序,这样子的场景用 if else就不合适了,楼主的这个场景我觉得不合适,纯粹就是为了表层代码看起来少了而已,没有普适性,不适合使用 pipeline

1年前 评论

laravel越来越复杂了

2年前 评论
❤seven 2年前

不怪你,是优雅害了laravel

2年前 评论

感觉还是when 和 scope好用, 可以复用的查询的比如用户id查询时间查询之类的 ,再单独封装一个Traits

10个月前 评论

这得新增好多class

10个月前 评论
if ($request->username) {
    $query->where('username', 'LIKE', "%$request->username%");
}

有十几个这样的要封装十几个类么。这样我会骂街的 :speak_no_evil:

2年前 评论

花里胡哨,不实用

2年前 评论

接手的人怕不是骂娘....还分出了那么多个类,后台查询一个页面十几个条件都有的

2年前 评论

食用方法

可还行 :joy:

2年前 评论

写的很好,下次别这样写了。
前两天论坛有篇对比存储库模式和 Active Record 模式的文章,里边有提到这种场景,最终业务逻辑过于依赖数据传参了,最好是可以根据业务场景把不同的 SQL 都固定下来,显然对于这种查询不可能有 9 x 9 = 81 种传参的可能性,但是后来看代码的人却不得不去考虑这种可能性

2年前 评论
秦晓武

scope就能实现吧?

2年前 评论

很棒 :+1:

2年前 评论
JaguarJack

花里胡哨!我选择 when

2年前 评论
kinge

这种不是屎山,代码逻辑越简单清晰越好,方便新人阅读

2年前 评论

看起来很牛批一样

2年前 评论

优雅,其他人看到了时候就懵了 :joy:

2年前 评论

几行代码的事让你写了好几个类,牛逼

2年前 评论

优雅是优雅,但是下一个看到你代码的,如果没看懂,就会从头到尾一直骂娘 :see_no_evil:

2年前 评论
随波逐流

这就屎山了?

2年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!