1. Go to this page and download the library: Download ez-php/search library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
use EzPhp\Search\Searchable;
use EzPhp\Search\SearchableInterface;
class Article implements SearchableInterface
{
use Searchable;
public function __construct(
public int $id,
public string $title,
public string $body,
) {}
public function getSearchableKey(): string|int
{
return $this->id;
}
// Optional overrides:
// public function searchableAs(): string { return 'articles'; }
// public function toSearchableArray(): array { return ['id' => $this->id, 'title' => $this->title]; }
}
use EzPhp\Search\SearchIndex;
use EzPhp\Search\SearchOptions;
$search = $app->make(SearchIndex::class);
$search->add($article);
$search->remove($article);
$result = $search->search('article', 'php tutorial');
foreach ($result->hits as $hit) {
echo $hit->id . ': ' . $hit->document['title'] . PHP_EOL;
}
$result = $search->search(
'article',
'php',
(new SearchOptions())->withLimit(10)->withOffset(0)->withFilter('status = "published"'),
);
$search->flush('article');
use EzPhp\Events\Event;
use EzPhp\Search\Listeners\SyncSearchIndex;
use EzPhp\Search\SearchIndex;
public function boot(): void
{
$index = $this->app->make(SearchIndex::class);
Event::listen(ArticleSaved::class, new SyncSearchIndex($index));
Event::listen(ArticleDeleted::class, new SyncSearchIndex($index, remove: true));
}
use EzPhp\Search\Listeners\HasSearchableModel;
use EzPhp\Search\SearchableInterface;
class ArticleSaved implements EventInterface, HasSearchableModel
{
public function __construct(private Article $article) {}
public function getSearchableModel(): SearchableInterface { return $this->article; }
}
use EzPhp\Search\SearchImportSources;
public function boot(): void
{
$this->app->make(SearchImportSources::class)
->register('articles', fn (): iterable => $this->app->make(ArticleRepository::class)->findAll());
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.