PHP code example of patchlevel / odm

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

    

patchlevel / odm example snippets


use Patchlevel\ODM\Attribute\Document;
use Patchlevel\ODM\Attribute\Id;
use Patchlevel\ODM\Attribute\Index;

#[Document('profiles')]
#[Index('by_status', ['status' => 'asc'])]
final class Profile
{
    /** @param list<Skill> $skills */
    public function __construct(
        #[Id]
        public readonly string $id,
        public string $name,
        public Status $status,
        public array $skills,
    ) {
    }
}

final readonly class Skill
{
    public function __construct(
        public string $value,
    ) {
    }
}

enum Status: string
{
    case ACTIVE = 'active';
    case INACTIVE = 'inactive';
}

use Patchlevel\ODM\Repository\RangoRepositoryManager;
use Patchlevel\Rango\Client;

$client = new Client($_ENV['POSTGRES_URI']);

$manager = RangoRepositoryManager::create($client);

use MongoDB\Client;
use Patchlevel\ODM\Repository\MongoDBRepositoryManager;

$client = new Client($_ENV['MONGODB_URI']);

$manager = MongoDBRepositoryManager::create($client);

$repository = $manager->get(Profile::class);

$repository->insert(
    new Profile('r-1', 'Rango', Status::ACTIVE, [new Skill('php')]),
    new Profile('r-2', 'Foo', Status::ACTIVE, [new Skill('node'), new Skill('js')]),
    new Profile('r-3', 'Bar', Status::INACTIVE, [new Skill('mongodb')]),
);

$profiles = $repository->findBy(
    filter: ['status' => Status::ACTIVE->value],
    sort: ['name' => 'asc'],
    limit: 10,
    offset: 0
);

$profile = $repository->get('r-2');
$profile->name = 'New Foo';
$repository->update($profile);

$repository->remove('r-3');