PHP code example of makermill / hydratype

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

    

makermill / hydratype example snippets


enum UserStatus: string
{
    case Active = 'active';
    case Disabled = 'disabled';
}

final class User
{
    public function __construct(
        private int $id,
        private string $displayName,
        private bool $enabled,
        private UserStatus $status,
    ) {
    }
}

use MakerMill\HydraType\HydraType;

$hydra = new HydraType();

$user = $hydra->hydrate(User::class, [
    'id' => '42',
    'display_name' => 'Ada Lovelace',
    'enabled' => 'yes',
    'status' => 'active',
]);

use MakerMill\HydraType\NamingConvention;

$camelData = $hydra->extract($user);
$snakeData = $hydra->extract($user, NamingConvention::SnakeCase);

$users = $hydra->hydrateMany(User::class, $inputRows);
$outputRows = $hydra->extractMany($users, NamingConvention::SnakeCase);

use MakerMill\HydraType\Assertions\NotEmpty;
use MakerMill\HydraType\Mutators\DateTimeFormat;
use MakerMill\HydraType\Mutators\JsonValue;
use MakerMill\HydraType\Mutators\Trim;
use MakerMill\HydraType\Rules\Optional;

final class Event
{
    #[Optional]
    private ?string $note = null;

    public function __construct(
        #[Trim]
        #[NotEmpty]
        private string $name,
        #[DateTimeFormat('Y-m-d H:i:s')]
        private DateTimeImmutable $startsAt,
        #[JsonValue]
        private array $metadata,
    ) {
    }
}

use MakerMill\HydraType\Configuration;
use MakerMill\HydraType\HydratorCache;

$configuration = new Configuration(
    hydratorDirectory: __DIR__ . '/../var/cache/hydratype',
);

(new HydratorCache($configuration))->warm(
    User::class,
    Order::class,
    Invoice::class,
);

use MakerMill\HydraType\CacheMode;
use MakerMill\HydraType\Configuration;
use MakerMill\HydraType\HydraType;

$hydra = new HydraType(new Configuration(
    hydratorDirectory: __DIR__ . '/../var/cache/hydratype',
    cacheMode: CacheMode::ReadOnly,
));