PHP code example of fostercommerce / meilisearch-connect

1. Go to this page and download the library: Download fostercommerce/meilisearch-connect 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/ */

    

fostercommerce / meilisearch-connect example snippets


'indices' => [
	'pages' => // ...
	'products' => // ...
]

'indices' => [
	'pages' => IndexBuilder::create()->withIndexId('pages_index')->build(),
	'products' => IndexBuilder::create()->withIndexId('products_index')->build(),
]

// config.php:
'indices' => [
	'pages' => IndexBuilder::create()
		->withIndexId(App::env('MEILISEARCH_PAGES_INDEX') ?? 'pages')
		->build(),
	'products' => IndexBuilder::create()
		->withIndexId(App::env('MEILISEARCH_PRODUCTS_INDEX') ?? 'products')
		->build(),
]

return [
	'meiliHostUrl' => 'http://localhost:7700',
	'meiliSearchApiKey' => '<Meilisearch Search Key>',
	'indices' => [
		'pages' => IndexBuilder::create()->build(),
	],
];

return [
	'meiliHostUrl' => 'http://localhost:7700',
	'meiliAdminApiKey' => '<Meilisearch Admin Key>',
	'meiliSearchApiKey' => '<Meilisearch Search Key>',
	'indices' => [
		'pages' => IndexBuilder::fromSettings(
			IndexSettingsBuilder::create()
				->withRanking([
					'customRanking:desc',
					'words',
					'exactness',
					'proximity',
					'attribute',
					'date:desc',
					'sort',
					'typo',
				])
				->withSearchableAttributes([
					'id',
					'title',
					'section',
				])
				->withFaceting([
					'maxValuesPerFacet' => 300,
				])
				->build()
		)
			->withElementQuery(
				Entry::find(), // Get all entries
				static fn (Entry $entry): array => [
					// Transform the entry
					'id' => $entry->id,
					'title' => $entry->title,
					'section' => $entry->section->handle ?? '',
					'url' => $entry->getUrl(),
					// Any other fields you want to 

Event::on(
	Product::class,
	Element::EVENT_AFTER_SAVE,
		static function (\craft\events\ModelEvent $event) {
		if (
			! ElementHelper::isDraft($event->sender) &&
			! $event->sender->resaving &&
			! ElementHelper::isRevision($event->sender)
		) {
			$item = $event->sender;
			$status = $item->getStatus();
			if ($status === Entry::STATUS_LIVE) {
				// If an entry is live, then we can add it to the index
				Queue::push(new SyncJob([
					'indexName' => 'pages',
					'identifier' => $item->id,
				]));
			} else {
				// Otherwise, we should make sure that it is not in the index
				Queue::push(new DeleteJob([
					'indexName' => 'pages',
					'identifier' => $item->id,
				]));
			}
		}
	}
);

Event::on(
	Product::class,
	Element::EVENT_AFTER_DELETE,
	static function (\craft\events\Event $event) {
		$item = $event->sender;
		Queue::push(new DeleteJob([
			'identifier' => $item->id,
		]));
	}
);