gpt4 book ai didi

php - Laravel:我所有模型的依赖注入(inject)和静态自定义方法

转载 作者:行者123 更新时间:2023-12-04 15:56:14 25 4
gpt4 key购买 nike

我创建了一个帮助类来搜索和过滤我的 laravel 模型(方法使用 tntsearch 和自定义范围),目前它工作得很好,但我想对其进行一些改进,遗憾的是它很难实现我想要的:

我要改进的地方:

1)能够在我的所有 laravel 模型上静态调用搜索方法,如下所示:

Model::search();

目前我必须实例化类并调用如下方法:
 $results = $searchHelper->search($request, $filters);

2)现在我还必须将两个参数传递给构造函数,在我的类中,我尝试在构造魔术方法中进行依赖注入(inject),但我仍然必须将请求和过滤器作为参数传递......

它在我的 Controller 中的外观:
public function search(Request $request, QueryFilters $filters)
{
$search = new Search($request, $filters);


$posts = $search->search('Post', ['postcategory', 'author', 'favorites']);

return response()->json([
'message' => 'Encontramos unas coincidencias',
'posts' => $posts,
], 200);
}

我的助手类:
<?php
namespace App\Helpers;


use Illuminate\Http\Request;
use App\Filters\QueryFilters;
use App\Filters\Filterable;


class Search
{

public $request;
public $filters;

public function __construct(Request $request, QueryFilters $filters)
{
$this->request = $request;
$this->filters = $filters;
}

public function search( $model, $relationships = [] )
{
$model = app("App\Models\".$model.");

$results = $model::search($this->request->input('search'), '')->get();

if(!$results->isEmpty())
{
$ids = implode(',', $results->pluck('id')->toArray());
$filters->merge(['whereIn' => $ids]);
}

$results = $model::filter($this->filters)->with($relationships)->paginate(10);

return $results;
}


}

我想调用这样的方法,不向构造函数传递参数(DI应该处理它),静态调用方法
Appointments::search();

最佳答案

您可以定义一个 Searchable像这样的特征(而不是你的 Search 类):

trait Searchable
{
public static function search($relationships = [])
{
//You may use the `resolve` method to resolve a class instance.
$request = resolve(\Illuminate\Http\Request::class);
//or $request = request();
$filters = resolve(\App\Filters\QueryFilters::class);

//rename the other `search` function on your model to `doSearch` to resolve conflicts
$results = self::doSearch($request->input('search'), '')->get();
//or using request helper function
//$results = self::doSearch(request('search'), '')->get();

if(!$results->isEmpty())
{
$ids = implode(',', $results->pluck('id')->toArray());
$filters->merge(['whereIn' => $ids]);
}

$results = self::filter($filters)->with($relationships)->paginate(10);

return $results;
}

}

并实现此 Searchable您的 Eloquent 模型的契约(Contract):

class Appointment extends Model
{
use Searchable;

//...
}

现在您可以调用:
Appointment::search();

关于php - Laravel:我所有模型的依赖注入(inject)和静态自定义方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59438688/

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