PHP code example of augustdai / hyperf-scout-meilisearch
1. Go to this page and download the library: Download augustdai/hyperf-scout-meilisearch 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/ */
augustdai / hyperf-scout-meilisearch example snippets
namespace App\Model;
use Hyperf\Scout\Searchable;
class Video extends Model
{
use Searchable;
public function searchableAs(): string
{
return 'Videos';
}
/**
* 只返回需要索引的字段,减少索引体积和导入耗时。
*/
public function toSearchableArray(): array
{
return [
'id' => $this->id,
'title' => $this->title,
'content' => $this->content,
'created_at' => $this->created_at?->toDateTimeString(),
];
}
public function getScoutKeyName(): string
{
return $this->getKeyName();
}
}
namespace Hyperf\Scout\Provider;
use GuzzleHttp\Client as GuzzleHttpClient;
use Hyperf\Contract\ConfigInterface;
use Hyperf\Guzzle\HandlerStackFactory;
use Hyperf\Scout\Engine\Engine;
use Hyperf\Scout\Engines\MeilisearchEngine;
use Http\Factory\Guzzle\RequestFactory;
use Http\Factory\Guzzle\StreamFactory;
use Meilisearch\Client;
use Psr\Container\ContainerInterface;
class MeilisearchProvider implements ProviderInterface
{
public function __construct(private ContainerInterface $container) {}
public function make(string $name): Engine
{
$config = $this->container->get(ConfigInterface::class);
$host = $config->get("scout.engine.{$name}.host");
$key = $config->get("scout.engine.{$name}.key");
$stack = (new HandlerStackFactory())->create(
['max_connections' => 256],
['retry' => false]
);
$guzzle = new GuzzleHttpClient([
'handler' => $stack,
'headers' => ['Accept-Encoding' => 'identity'], // 禁用压缩,避免协程环境解压失败
'expect' => false, // 禁用 100-Continue,防止大请求体 rewind 失败
]);
$client = new Client($host, $key, $guzzle, new RequestFactory(), [], new StreamFactory());
return new MeilisearchEngine($client);
}
}