PHP code example of seredoff / evolve-orm

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

    

seredoff / evolve-orm example snippets


use EvolveORM\Hydrator;

class User {
    public int $id;
    public string $name;
    public array $roles;
}

$data = [
    'id' => 1,
    'name' => 'Иван Иванов',
    'roles' => ['admin', 'editor']
];

$hydrator = Hydrator::create();

$user = $hydrator->hydrate(User::class, $data);

echo $user->id;    // Выведет: 1
echo $user->name;  // Выведет: Иван Иванов
print_r($user->roles); // Выведет: Array ( [0] => admin [1] => editor )

// Для гидрации нескольких объектов можно использовать метод `hydrateAll`

$dataSet = [
    ['id' => 1, 'name' => 'Иван Иванов', 'roles' => ['admin']],
    ['id' => 2, 'name' => 'Петр Петров', 'roles' => ['editor']]
];

$users = $hydrator->hydrateAll(User::class, $dataSet);

// $users теперь содержит массив объектов User

final readonly class Trip
{
    /** @var Passenger[] */
    #[OrmMapper(ToPassengerCollectionMapper::class)]
    public array $passengers;

    public function __construct(
        public Id $id,
        public DateTimeImmutable $date,
        public Route $route,
        public Bus $bus,
        public Driver $driver,
        Passenger ...$passengers
    ) {
        $this->passengers = $passengers;
    }
}

final readonly class Route
{
    /** @var Point[] */
    #[OrmMapper(ToPointsCollectionMapper::class)]
    public array $points;

    public function __construct(
        public Id $id,
        public string $title,
        public Duration $duration,
        Point ...$point
    ) {
        $this->points = $point;
    }
}

// ... другие классы (Bus, Driver, Passenger, Luggage и т.д.)

$hydrator = new Hydrator(
    $cache,
    [
        Driver::class => [
            'phone' => ToNullablePhoneMapper::class,
        ],
        Passenger::class => [
            'luggage' => ToLuggageCollectionMapper::class,
            'ticket' => ToNullableTicketMapper::class,
        ],
        Route::class => [
            'points' => ToPointsCollectionMapper::class,
        ],
        Trip::class => [
            'passengers' => ToPassengerCollectionMapper::class,
        ],
    ],
);

$inputData = [
    "id_value" => "6076e7ca-930d-44d4-b229-6a8b36cf7027",
    "date" => "2017-01-10 22:15:44",
    "bus_number" => 74312320,
    "bus_model_title" => "inventore",
    "bus_model_year" => 1980,
    "driver_id_value" => "341ce09e-5cc0-4905-8472-265245703aaa",
    "driver_name_firstName" => "Lionel",
    "driver_name_lastName" => "O'Reilly",
    "driver_name_secondName" => null,
    "driver_phone_value" => "1-541-897-9141",
    "route_id_value" => "route1",
    "route_title" => "route 1",
    "route_duration_seconds" => 7200,
    "route_points" => [
        [
            "title" => "point 1",
            "latitude" => 1.0,
            "longitude" => 1.0,
            "arrivalTime" => "1970-01-01 08:00:00"
        ],
        // ...
    ],
    "passengers" => [
        [
            "id_value" => "4f799cfc-087a-437f-8fa9-66a2fb8c3eb0",
            "seat_number" => 94198656,
            "ticket_price_cents" => 695,
            "ticket_dateTime" => "1984-09-02 12:15:52",
            "luggage" => [
                [
                    "id_value" => "dd752a21-a2c4-4645-9fb4-83aeac0d7cde",
                    "type" => "small",
                    "overallDimensions_height" => 266.0,
                    "overallDimensions_width" => 1422.43916487,
                    "overallDimensions_length" => 18331.49081372,
                    "overallDimensions_weight" => 0.0
                ],
                // ...
            ]
        ],
        // ...
    ]
];

$trip = $hydrator->hydrate(Trip::class, $inputData);

use EvolveORM\Bundle\Orm\Mapper;

class UcfirstMapper implements Mapper
{
    public function __invoke(mixed $value, Hydrator $hydrator): mixed
    {
        // логика объектно-реляционного отображения...
        return ucfirst($value);
    }
}

class UpperMapper implements Mapper
{
    public function __invoke(mixed $value, Hydrator $hydrator): mixed
    {
        // логика объектно-реляционного отображения...
        if (!is_array($value)) {
            throw new RuntimeException('Unexpected value type');
        }    

        return array_map(
            static fn(string $role): string => mb_strtoupper($role),
            $value,
        );
    }
}

use EvolveORM\Hydrator;
use EvolveORM\Bundle\Attribute\OrmMapper;
use EvolveORM\Bundle\Cache\WeakRefReflectionCache;

class User {
    public int $id;
    public string $name;
    #[OrmMapper(UpperMapper::class)]
    public array $roles;
}

$data = [
    'id' => 1,
    'name' => 'иван',
    'roles' => ['admin', 'editor']
];

$cache = new WeakRefReflectionCache();

$hydrator = new Hydrator(
    $cache,
    [
        User::class => [
            'name' => UcfirstMapper::class,
        ],
    ],
);

$user = $hydrator->hydrate(User::class, $data);

echo $user->id;    // Выведет: 1
echo $user->name;  // Выведет: Иван
print_r($user->roles); // Выведет: Array ( [0] => ADMIN [1] => EDITOR )

class MyCustomStrategy implements HydrationStrategy
{
    public function canHydrate(ReflectionProperty $property, mixed $value): bool
    {
        // Логика определения, может ли стратегия обработать свойство
    }

    public function hydrate(object $object, ReflectionProperty $property, mixed $value): void
    {
        // Логика гидрации свойства
    }    
}

$customStrategies = [
    new MyCustomStrategy(),
    new AnotherCustomStrategy(),
];

$hydrator = new Hydrator($reflectionCache, $ormConfig, $customStrategies);

$cache->clear();