PHP code example of guennichi / mapper

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

    

guennichi / mapper example snippets


use Guennichi\Mapper\Mapper;
use Guennichi\Mapper\Metadata\ConstructorFetcher;
use Guennichi\Mapper\Metadata\Factory\ArgumentFactory;
use Guennichi\Mapper\Metadata\Factory\ArgumentTypeFactory;
use Guennichi\Mapper\Metadata\Factory\ConstructorFactory;
use Guennichi\Mapper\Metadata\Factory\PhpDocumentorArgumentTypeFactory;
use Guennichi\Mapper\Metadata\Factory\ReflectionArgumentTypeFactory;
use Guennichi\Mapper\Metadata\Repository\InMemoryConstructorRepository;

// Create the mapper
$mapper = new Mapper(
    new ConstructorFetcher(
        new ConstructorFactory(
            new ArgumentFactory(
                new ArgumentTypeFactory(
                    new PhpDocumentorArgumentTypeFactory(),
                    new ReflectionArgumentTypeFactory(),
                ),
            ),
        ),
        new InMemoryConstructorRepository(),
    ),
);

// Define your class
final class Product
{
    public function __construct(
        public readonly string $name,
        public readonly float $price,
    ) {}
}

// Map array to object
$data = ['name' => 'Laptop', 'price' => 999.99];
$product = $mapper($data, Product::class);

use Guennichi\Mapper\Attribute\DateTimeFormat;
use Guennichi\Mapper\Attribute\Flexible;
use Guennichi\Mapper\Attribute\Name;

final class ApiProduct
{
    public function __construct(
        #[Name('productName')] // Map 'productName' to $name
        public readonly string $name,
        #[Flexible] // Convert 'yes'/'no' to boolean
        public readonly bool $active,
        #[DateTimeFormat('Y-m-d')] // Custom date format
        public readonly \DateTimeInterface $createdAt,
    ) {}
}

$apiResponse = [
    'productName' => 'Gaming Laptop',
    'active' => 'yes', // Converted to true
    'createdAt' => '2023-02-10',
];

$product = $mapper($apiResponse, ApiProduct::class);

$serialized = serialize($product);
$product = unserialize($serialized);

$data = json_encode(['name' => $product->name, 'price' => $product->price]);
$product = $mapper(json_decode($data, true), Product::class);