代码重构-改进重复查询生成器的调用以提高可读性

问题描述

所以我在同一模型的许多部分重复了相同的代码,但是在不同的功能上重复了它。这是一个示例:

$records = AuditLogEntry::whereIn('context_type',['Type1','Type2'])
        ->whereContextId($this->id)
        ->whereIn('event_type',[config('constants.audit_log.EVENT_TYPE_UPDATE'),config('constants.audit_log.EVENT_TYPE_CANCEL')])
        ->whereDate('created_at','>',$date)
        ->select(['id','Meta','event_type'])
        ->orderByDesc('created_at')
        ->get();

在另一个函数中,我也有类似的代码块(请注意最后四行代码):

$records2 = AuditLogEntry::whereContextType('Type3')
            ->whereEventType(config('constants.audit_log.EVENT_TYPE_EXERCISE'))
            ->whereIn('context_id',$contexts->toArray())
            ->whereDate('created_at',$date)
            ->select(['Meta','event_type'])
            ->orderByDesc('created_at')
            ->get();

所以我的想法只是在这些行上进行简单的代码重构:

 ->whereDate('created_at','event_type'])
            ->orderByDesc('created_at')
            ->get();

因为在我的模型的许多地方都需要它们,所以我试图使用回调来执行此代码重构,如下所示:

private function recordsQuery(string $date): Closure
{
    return function ($query) use ($date) {
        $query->whereDate('created_at','event_type'])
            ->orderByDesc('created_at')
            ->get();
    };
}

因此,我可以消除这4行代码,并得到以下内容

$exercises = AuditLogEntry::whereContextType('Exercise')
            ->whereEventType(config('constants.audit_log.EVENT_TYPE_EXERCISE'))
            ->whereIn('context_id',$grantsExercised->pluck('id')->toArray())
            ->$this->recordsQuery(); /** This is not working,obvIoUsly but you guys can get the idea of what I'm trying to do */

所以问题是我想使用链接来提高可读性,我在想是否可以使用宏并扩展包括此新功能查询生成器。当然,我想听听您的意见,看看有人是否有更好的主意。

感谢您的帮助:)

解决方法

您可以通过查询范围来实现:https://laravel.com/docs/7.x/eloquent#local-scopes