1. Go to this page and download the library: Download php-es-orm/es-orm 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 EsOrm\Client\ConnectionManager;
use EsOrm\Model\Model;
use EsOrm\Support\Config;
Model::setConnectionManager(new ConnectionManager(Config::fromFile('config/es_orm.php')));
// or from an array
Model::setConnectionManager(ConnectionManager::fromArray([
'default' => 'default',
'connections' => ['default' => ['hosts' => ['http://localhost:9200']]],
]));
declare(strict_types=1);
namespace App\Models;
use EsOrm\Model\Model;
final class User extends Model
{
protected string $index = 'users';
protected array $fillable = [
'name',
'email',
'age',
'status',
];
protected array $casts = [
'age' => 'integer',
'active' => 'boolean',
'metadata' => 'array',
'created_at' => 'datetime',
];
}
// Find by attributes or return an unsaved instance hydrated with the values
$user = User::query()->firstOrNew(['email' => '[email protected]'], ['name' => 'Tom']);
// Find by attributes or create the document (single index request when missing)
$user = User::query()->firstOrCreate(['email' => '[email protected]'], ['name' => 'Tom']);
// Find by attributes and create/update with the given values
$user = User::query()->updateOrCreate(['email' => '[email protected]'], ['age' => 21]);
$user->increment('login_count');
$user->increment('balance', 25, ['status' => 'vip']); // extra attributes in the same request
$user->decrement('balance', 10);
// Existence and single-record assertions
User::query()->where('status', 'active')->exists(); // bool
User::query()->where('email', $email)->sole(); // User, throws when 0 or > 1 match
// Metric shortcuts (a size-0 search with a single value aggregation)
User::query()->where('status', 'active')->avg('age'); // int|float|null
User::query()->sum('price');
User::query()->min('created_at');
User::query()->max('created_at');
// Delete every document matching the query (_delete_by_query, hard delete)
User::query()->where('status', 'banned')->deleteByQuery(['refresh' => true]);
User::query()->each(function (User $user): void {
// export / migrate / batch process
}, chunkSize: 1000);
// Break out of the iteration by returning false
User::query()->each(function (User $user): bool {
return $user->age < 100; // stop at the first user older than 100
});
$users = User::bulkCreate([...]);
$count = User::bulkUpdate([...]); // each row must contain the primary key
$count = User::bulkDelete([...]);
// Multi get (single request)
$users = User::mget([1, 2, 3]);
// Multi search: one _msearch request for many queries
use EsOrm\Query\Search;
$results = Search::multi([
'users' => User::query()->match('name', 'Tom'),
'articles' => Article::query()->term('status', 'published'),
]);
$results['users']->hits(); // ModelCollection
$results['users']->total(); // int
use EsOrm\Model\Attribute;
final class User extends Model
{
protected function name(): Attribute
{
return Attribute::make(
get: fn ($value) => ucfirst((string) $value),
set: fn ($value) => strtolower((string) $value),
);
}
}
final class User extends Model
{
public function scopeActive($query)
{
return $query->term('status', 'active');
}
}
User::active()->get(); // via __callStatic -> query()
User::query()->active()->get();
use EsOrm\Scope\Scope;
Model::addGlobalScope(new class implements Scope {
public function apply(\EsOrm\Contracts\QueryBuilderInterface $builder): void
{
$builder->term('tenant_id', 7);
}
});
use EsOrm\Model\Model;
use EsOrm\Model\SoftDeletes;
final class User extends Model
{
use SoftDeletes;
protected string $index = 'users';
protected array $casts = ['deleted_at' => 'datetime'];
}
$user->delete(); // sets deleted_at, keeps the document
$user->trashed(); // bool
$user->restore(); // clears deleted_at
$user->forceDelete(); // removes the document
User::query()->get(); // excludes trashed
User::withTrashed()->get(); //
use EsOrm\Model\Model;
Model::eventDispatcher()->listen('created', function (Model $model): void {
// ...
});
// A listener returning false aborts the operation (e.g. saving/creating/deleting)
// Observers
final class UserObserver
{
public function created(User $user): void {}
public function updated(User $user): void {}
public function deleted(User $user): void {}
}
User::observe(UserObserver::class);
final class Article extends Model
{
protected string $index = 'articles';
public function author(): \EsOrm\Relation\BelongsTo
{
return $this->belongsTo(Author::class, 'author_id');
}
}
final class Author extends Model
{
protected string $index = 'authors';
public function articles(): \EsOrm\Relation\HasMany
{
return $this->hasMany(Article::class, 'author_id');
}
}
// Eager load in a single batch query
$articles = Article::with('author')->get();
// Lazy eager load on loaded models
$article->load('author');
$article->loadMissing('author');
declare(strict_types=1);
namespace Database\EsMigrations;
use EsOrm\Migration\IndexMigration;
use EsOrm\Mapping\Mapping;
final class CreateArticlesIndex extends IndexMigration
{
public function up(): void
{
$this->createIndex('articles', Mapping::create('articles')
->text('title')
->keyword('status')
->date('created_at'));
}
public function down(): void
{
$this->deleteIndex('articles');
}
}
use EsOrm\Migration\Migrator;
$migrator = new Migrator($indices, 'database/es-migrations');
$migrator->migrate(); // apply pending migrations
$migrator->rollback(1); // roll back the last batch
$migrator->status(); // list the discovered migrations and their state
bash
AppServiceProvider.php
use EsOrm\Contracts\ConnectionManagerInterface;
public function register(): void
{
$this->app->make(ConnectionManagerInterface::class);
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.