Last active
November 6, 2024 14:28
-
-
Save driesvints/2257e79d361efa3911e8cdf331e70d79 to your computer and use it in GitHub Desktop.
Invokable query object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$searchThreads = app(\App\Queries\SearchThreads::class); | |
// As a default value. | |
$results = array_get($someArray, 'foo', $searchThreads) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Queries; | |
use App\Models\Thread; | |
use Illuminate\Contracts\Pagination\Paginator; | |
class SearchThreads | |
{ | |
public function __construct() | |
{ | |
// gets resolved through IoC. | |
} | |
/** | |
* @return \App\Models\Thread[] | |
*/ | |
public static function get(string $keyword, int $perPage = 20): Paginator | |
{ | |
return Thread::feedQuery() | |
->where('threads.subject', 'LIKE', "%$keyword%") | |
->orWhere('threads.body', 'LIKE', "%$keyword%") | |
->paginate($perPage); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Controllers\Forum; | |
use App\Queries\SearchThreads; | |
use App\Http\Middleware\RedirectIfUnconfirmed; | |
class ThreadsController extends Controller | |
{ | |
public function overview(SearchThreads $searchThreads) | |
{ | |
$threads = $searchThreads(request('search')); | |
return view('forum.overview', compact('threads')); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, I'm sorry but I can't understand how you can invoke something without the magic method.
In the closure_example, for me you don't invoke anything, but just return an empty object.
In the controller I'm ok you invoke it, but for me, the
__invoke
is missing:Am I wrong?
Thx