PHP code example of ttbooking / data-mapper

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

    

ttbooking / data-mapper example snippets



use DataMapper\Elements\DataMapper;
/**
 * Описание структуры объекта
 */
class Example extends DataMapper {
    public string $property;
}

...

/**
 * Использование
 */
$item = Example::map(['property' => 'value']);
echo $item->property; // value

/**
 * Массив данных
 */
$items = Example::mapMany([
    ['property' => 'value'],
    ['property' => 'value2']
]);


use DataMapper\Attributes\ManyOf;
class Example extends DataMapper {
    #[ManyOf('int')]
    public array $values;
}
$item = Example::map(['values' => ['1', 3, '5', '0']]);
/**
 * $item->values = [1, 3, 5, 0];
 */

use DataMapper\Attributes\FromName;
use DataMapper\Attributes\ManyOf;
use DataMapper\Attributes\ToName;

class Example extends DataMapper {
    #[ManyOf('int'), FromName('integers'), ToName('integerValues')]
    public array $values;
}
$item = Example::map(['integers' => ['1', 3, '5', '0']]);
/**
 * $item->values === [1, 3, 5, 0];
 * $item->toArray() === ['integerValues' => [1, 3, 5, 0]]
 */

use DataMapper\Attributes\Caster;
use DataMapper\Casters\DateTimeCaster;

class Example extends DataMapper {
    //              формат входящей даты, формат сериализации, часовой пояс
    #[Caster(DateTimeCaster::class, 'Y-m-d', 'd.m.Y', 'Europe/Kaliningrad')]
    public Carbon $date;
}

$example = Example::map([
    'date' => '20.11.2020'
]);

$example->toJson(); // {"date": "2020-11-20"}