PHP code example of melia / object-storage

1. Go to this page and download the library: Download melia/object-storage 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/ */

    

melia / object-storage example snippets



use melia\ObjectStorage\ObjectStorage;

$storage = new ObjectStorage(__DIR__ . '/var/object-storage');

// Build a small graph
$child  = new ChildObject('child-1');
$parent = new ParentObject('parent-1', $child);

// Store graph (references are auto-managed)
$uuid = $storage->store($parent);

// Load later
$loaded = $storage->load($uuid);
echo $loaded->name;         // "parent-1"
echo $loaded->child->name;  // Lazy loads "child-1"


$storage = new ObjectStorage(__DIR__.'/var/objects');

$child  = new ChildObject('child-X');
$parent = new ParentObject('parent-X', $child);

$uuid = $storage->store($parent);

$p = $storage->load($uuid);        // child is lazy
echo $p->child->name;              // triggers load and parent replacement
$p->child->name = 'child-X2';
$storage->store($p);               // persists changes


use melia\ObjectStorage\ObjectStorage;

$storage = new ObjectStorage(__DIR__ . '/var/object-storage');
$uuid = '...'; // existing object id

// Read-Modify-Write with exclusive lock + simple retry
$attempts = 0;
$maxAttempts = 3;

do {
    try {
        // 1) Acquire exclusive lock for this object
        $obj = $storage->load($uuid, true); // exclusive
        
        // 2) Modify under lock
        $obj->title = 'Updated Title ' . time();

        // 3) Persist while still holding the lock
        $storage->store($obj);

        // 4) Done: lock is released after operations finish
        break;
    } catch (\Throwable $e) {
        $attempts++;
        if ($attempts >= $maxAttempts) {
            // Could log and rethrow or return a 423 Locked in an API context
            throw $e;
        }
        // Back off briefly before retrying to avoid lock contention
        usleep(200_000 * $attempts); // 200ms, 400ms, 600ms
    }
} while ($storage->getLockAdapter()->isLockedByOtherProcess($uuid));


use melia\ObjectStorage\ObjectStorage;
use melia\ObjectStorage\Event\Events;
use melia\ObjectStorage\Event\DispatcherInterface;
use melia\ObjectStorage\Event\Context\Context;
use melia\ObjectStorage\Event\Context\ObjectPersistenceContext;
use melia\ObjectStorage\Event\Context\ClassnameChangeContext;
use melia\ObjectStorage\Event\Context\LifetimeContext;
use melia\ObjectStorage\Event\Context\StubContext;
use melia\ObjectStorage\Event\Context\TypeConversionContext;
use melia\ObjectStorage\Event\Context\LazyTypeNotSupportedContext;

// Initialize storage (using defaults)
$storage = new ObjectStorage(__DIR__ . '/var/object-storage');

// Get the dispatcher and register listeners
/** @var DispatcherInterface $dispatcher */
$dispatcher = $storage->getEventDispatcher();

// Called before an object is stored
$dispatcher->addListener(Events::BEFORE_STORE, function (ObjectPersistenceContext $ctx) {
    // $ctx->getUuid()
});

// Called after an object is stored (with previous object if available)
$dispatcher->addListener(Events::OBJECT_SAVED, function (ObjectPersistenceContext $ctx) {
    // $ctx->getUuid(), $ctx->getObject(), $ctx->getPreviousObject()
});

// Called after metadata is saved
$dispatcher->addListener(Events::METADATA_SAVED, function (Context $ctx) {
    // $ctx->getUuid()
});

// Called before and after load
$dispatcher->addListener(Events::BEFORE_LOAD, function (Context $ctx) {});
$dispatcher->addListener(Events::AFTER_LOAD, function (Context $ctx) {});

// Cache hit during load
$dispatcher->addListener(Events::CACHE_HIT, function (Context $ctx) {});

// Object expired during load
$dispatcher->addListener(Events::OBJECT_EXPIRED, function (Context $ctx) {});

// Lifetime changed via setExpiration/setLifetime
$dispatcher->addListener(Events::LIFETIME_CHANGED, function (LifetimeContext $ctx) {
    // $ctx->getUuid(), $ctx->getExpiresAt()
});

// Stub files created/removed
$dispatcher->addListener(Events::STUB_CREATED, function (StubContext $ctx) {
    // $ctx->getUuid(), $ctx->getClassName()
});
$dispatcher->addListener(Events::STUB_REMOVED, function (StubContext $ctx) {});

// Classname changed for existing UUID
$dispatcher->addListener(Events::CLASSNAME_CHANGED, function (ClassnameChangeContext $ctx) {
    // $ctx->getUuid(), $ctx->getPreviousClassname(), $ctx->getNewClassname()
});

// After delete
$dispatcher->addListener(Events::AFTER_DELETE, function (Context $ctx) {});

// Clear cache
$dispatcher->addListener(Events::CACHE_CLEARED, function () {});

// Shared lock acquired
$dispatcher->addListener(Events::SHARED_LOCK_ACQUIRED, function (Context $ctx) {});

// Exclusive lock acquired
$dispatcher->addListener(Events::EXCLUSIVE_LOCK_ACQUIRED, function (Context $ctx) {});

// Lock released
$dispatcher->addListener(Events::LOCK_RELEASED, function (Context $ctx) {});

// Safe mode enabled
$dispatcher->addListener(Events::SAFE_MODE_ENABLED, function () {});

// Safe mode disabled
$dispatcher->addListener(Events::SAFE_MODE_DISABLED, function () {});

// Lazy type isn't supported
$dispatcher->addListener(Events::LAZY_TYPE_NOT_SUPPORTED, function (LazyTypeNotSupportedContext $ctx) {
    // $ctx->getClassName(), $ctx->getPropertyName()
}

// Cache entry added
$dispatcher->addListener(Events::CACHE_ENTRY_ADDED, function (Context $ctx) {});

// Cache entry removed
$dispatcher->addListener(Events::CACHE_ENTRY_REMOVED, function (Context $ctx) {});

// Use storage as usual
$uuid = $storage->store((object)['name' => 'Alice']);
$loaded = $storage->load($uuid);
$storage->delete($uuid);


use melia\ObjectStorage\ObjectStorage;
use melia\ObjectStorage\Runtime\ClassRenameMap;

$storage = new ObjectStorage(__DIR__ . '/var/object-storage');

$map = new ClassRenameMap();
$map->createAlias(\Legacy\OldUser::class, \App\Domain\User::class);
$storage->setClassRenameMap($map);

$loaded = $storage->load($uuid); // Instance of \App\Domain\User