PHP code example of rogerthomas84 / dtoinflator

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

    

rogerthomas84 / dtoinflator example snippets



namespace MyNamespace;

class Person extends \DtoInflator\DtoInflatorAbstract
{
    public $name;
    public $age;
}

$data = [
    'name' => 'Joe',
    'age' => 35
];
$inflated = Person::inflateSingleArray($data);


namespace MyNamespace;

class Person extends \DtoInflator\DtoInflatorAbstract
{
    public $name;
    public $age;
}

$data = [
    [
        'name' => 'Joe',
        'age' => 35
    ],
    [
        'name' => 'Jane',
        'age' => 34
    ]
];
$inflated = Person::inflateSingleArray($data);


namespace MyNamespace;

class Favourite extends \DtoInflator\DtoInflatorAbstract
{
    /**
     * @var string
     */
    public $candy;
}

class ColorItem extends \DtoInflator\DtoInflatorAbstract
{
    /**
     * @var string
     */
    public $name;
}

class Person extends \DtoInflator\DtoInflatorAbstract
{
    /**
     * @var string
     */
    public $firstName;

    /**
     * @var int
     */
    public $age;

    /**
     * @var Favourite
     */
    public $favs;

    /**
     * @var ColorItem[]
     */
    public $colors;

    /**
     * @param array
     */
    protected $fieldToFieldMap = [
        'name' => 'firstName' // maps the source key of `name` to the object property of `firstName`
    ];

    /**
     * @param array
     */
    protected $keyToClassMap = [
        'favs' => '\MyNamespace\Favourite',  // maps the object property of `favs` to an instance of the `Favourite` object
        'colors' => '\MyNamespace\ColorItem[]'   // maps the object property of `colors` to an array of `ColorItem` objects
    ];
}

$data = [
    'name' => 'Joe',
    'age' => 35,
    'favs' => [
        'candy' => 'chocolate'
    ],
    'colors' => [
        [
            'name' => 'blue'
        ],
        [
            'name' => 'red'
        ]
    ]
];
$inflated = Person::inflateSingleArray($data);

// Or, if you're using an object initially.
$candyBar = new stdClass();
$candyBar->candy = 'chocolate';
$colorOne = new stdClass();
$colorOne->name = 'blue';
$colorTwo = new stdClass();
$colorTwo->name = 'red';

$data = new stdClass();
$data->name = 'Joe';
$data->age = 35;
$data->favs = [
    $candyBar
];
$data->colors = [
    $colorOne,
    $colorTwo
];
$inflated = Person::inflateSingleObject($data);

protected $keyToClassMap = [
    'favourite' => '\MyNamespace\Favourite'
];

protected $keyToClassMap = [
    'favourites' => '\MyNamespace\Favourite[]'
];