PHP code example of maduser / argon-dto

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

    

maduser / argon-dto example snippets


use Maduser\Argon\DTO\AbstractDTO;

final class ProductDTO extends AbstractDTO
{
    public function __construct(
        public readonly int $id,
        public readonly string $name
    ) {}
}

$dto = new ProductDTO(1, 'Gadget');

use Maduser\Argon\DTO\AbstractDTO;
use Maduser\Argon\DTO\Contracts\AutoMappableInterface;
use Maduser\Argon\DTO\Traits\AutoMap;

final class UserDTO extends AbstractDTO implements AutoMappableInterface
{
    use AutoMap;

    public const MAPPABLE_FIELDS = ['id', 'name'];

    public function __construct(
        public readonly int $id,
        public readonly string $name
    ) {}
}

$dto = UserDTO::fromArray(['id' => 1, 'name' => 'Alice']);
$dto = UserDTO::fromJson('{"id":1,"name":"Alice"}');

$array = $dto->toArray();
$json = $dto->toJson();

public static function mapFromArray(array $data): array
{
    $fqcn = static::class;

    if (!defined("$fqcn::MAPPABLE_FIELDS")) {
        throw DTOMappingException::missingMap($fqcn);
    }

    /** @var list<string> $fields */
    $fields = constant("$fqcn::MAPPABLE_FIELDS");

    return array_map(
        static function (string $key) use ($data, $fqcn): mixed {
            if (!array_key_exists($key, $data)) {
                throw DTOMappingException::missingField($key, $fqcn);
            }
            return $data[$key];
        },
        $fields
    );
}