知識點: 模板方法模式
ConsultController中
Consult模型中
ConsultFilters類
Filters抽象類
<?php
namespace App\Filters;
/*過濾器抽象類*/
use Illuminate\Http\Request;
abstract class Filters
{
/**
* @var Request
*/
protected $request;
/**
* The Eloquent builder.
*
* @var \Illuminate\Database\Eloquent\Builder
*/
protected $builder;
/**
* Registered filters to operate upon.
*
* @var array
*/
protected $filters = [];
/**
* Create a new ThreadFilters instance.
*
* @param Request $request
*/
public function __construct(Request $request)
{
$this->request = $request;
}
/**
* Apply the filters.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @return \Illuminate\Database\Eloquent\Builder
*/
public function apply($builder)
{
$this->builder = $builder;
foreach ($this->getFilters() as $filter => $value) {
if (method_exists($this, $filter)) {
$this->$filter($value);
}
}
return $this->builder;
}
/**
* Fetch all relevant filters from the request.
*
* @return array
*/
public function getFilters()
{
return array_filter($this->request->only($this->filters)); //Laravel5.5中已將intersect棄用,5.5以下使用下面的語句
//return $this->request->intersect($this->filters); //request和filters陣列取交集
}
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結