PHP code example of isswp101 / elasticsearch-eloquent

1. Go to this page and download the library: Download isswp101/elasticsearch-eloquent 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/ */

    

isswp101 / elasticsearch-eloquent example snippets


use Isswp101\Persimmon\Models\BaseElasticsearchModel;
use Isswp101\Persimmon\Persistence\Persistence;
use Isswp101\Persimmon\Contracts\PersistenceContract;

class Product extends BaseElasticsearchModel
{
    protected string $index = 'index';
    protected string|null $type = 'type'; // optional

    // If you have a pre-configured Elasticsearch client you can pass it here (optional)
    public function createPersistence(): PersistenceContract
    {
        return new Persistence($client);
    }
}

$product = Product::create([
    'id' => 1, 
    'name' => 'Product',
    'price' => 10
]);

$product = new Product();
$product->id = 1;
$product->name = 'Product';
$product->price = 10;
$product->save();

$product = Product::find(1);

$product = Product::find(1, ['name']);

$product = Product::find(1, ['name']);  // from elasticsearch
$product = Product::find(1, ['name']);  // from cache
$product = Product::find(1, ['price']); // from elasticsearch
$product = Product::find(1, ['price']); // from cache
$product = Product::find(1, ['name']);  // from cache

$product = Product::find(1);            // from elasticsearch
$product = Product::find(1);            // from cache
$product = Product::find(1, ['name']);  // from cache
$product = Product::find(1, ['price']); // from cache

$product = Product::find(1, ['name']);
$product->name = 'Name';
$product->save(['name']);

$product = Product::find(1);
$product->delete();

Product::destroy(1);

use Isswp101\Persimmon\Models\BaseElasticsearchModel;

class Product extends BaseElasticsearchModel
{
    protected function saving(): bool
    {
        // Disable update if it's free
        return $this->price <= 0;
    }

    protected function deleting(): bool
    {
        if ($this->user_id != 1) {
            throw new DomainException('No permissions to delete this model');
        }

        return true;
    }
}

$product = Product::first($query);

$product = Product::firstOrFail($query);

$products = Product::search($query);

$products = Product::all($query);