简体   繁体   中英

Using functions in Laravel macros

I would like to extend Eloquent Builder to have a support for search 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.

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.

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?

I have ended up creating a class which would contain the complete logic I need. I see this as a fairly good OOP practice.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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