简体   繁体   English

在 Laravel 宏中使用函数

[英]Using functions in Laravel macros

I would like to extend Eloquent Builder to have a support for search function.我想扩展 Eloquent Builder 以支持搜索 function。 Inside my service provider I've added the following:在我的服务提供商内部,我添加了以下内容:

Builder::macro('search', function (string $searchBy) {
    ...
}

which works.哪个有效。 I can now call a search method on my model.我现在可以在我的 model 上调用搜索方法。

The issue I'm having is that the logic within it is getting a rather complex and I wouldn't like it to be a single large script, however splitting to functions doesn't work since scope when inside a macro callback is actually from Eloquent Builder.我遇到的问题是其中的逻辑变得相当复杂,我不希望它是一个大脚本,但是由于 scope 内部macro回调实际上来自 Eloquent,因此拆分为函数不起作用生成器。

So this doesn't work:所以这不起作用:

public function foo()
{
    dd('bar');
}

public function boot()
{
    Builder::macro('search', function (string $searchBy) {
        $this->bla();
        ...
    }
}

Is there a way to use functions without going over the hassle of extending complete Eloquent Builder?有没有一种方法可以使用功能而无需扩展完整的 Eloquent Builder?

I have ended up creating a class which would contain the complete logic I need.我最终创建了一个包含我需要的完整逻辑的 class。 I see this as a fairly good OOP practice.我认为这是一个相当不错的 OOP 实践。

Builder::macro('search', function (array $input) {
    $jsonQuery = new JsonQuery($this, $input);
    $jsonQuery->search();

    return $this;
});

For anyone interested in details, you can check out my JSON search package .对于任何对细节感兴趣的人,您可以查看我的 JSON 搜索 package

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM