PHP code example of alexpts / php-hydrator

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

    

alexpts / php-hydrator example snippets


$extractor = new Extractor;
$normalizer = new \PTS\Hydrator\Normalizer;

$model = new Model([
    'id' => 1,
    'name' => 'Alex'
    'email' => '[email protected]'
]);

$rules = [
   'id' => [], // prop as dto`s key
   'name' => [
	   'prop' => 'name', // prop is name field in model
   ],
   'email' => [
	   'get' => 'getEmail', // getter $model->getEmail();
   ]
];
$rules = $normalizer->normalize($rules);

$extractor->extract($model, $rules)


$rules = [
   'login' => [
	   'prop' => 'name',
   ],
   ...
];
$extractor->extract($model, $rules);


$rules = [
   'name' => [],
   ...
];
$rules = $normalizer->normalize($rules);

$extractor->extract($model, $rules)


$rules = [
   'name' => [
	   'get' => 'getName', // getter $model->getName();
   ],
];

$extractor->extract($model, $rules);

$hydrator = new Hydrator;

$dto = [
    'id' => 1,
    'login' => 'Alex'
    'email' => '[email protected]
];

$rules = [
	'id' => [], // prop as dto`s key
	'login' => [
		'prop' => 'name', // dto key login fill property name
	],
	'email' => [
		'set' => 'setEmail', // setter $model->setEmail();
	]
];
$rules = $normalizer->normalize($rules);

$model = $hydrator->hydrate($dto, Model::class, $rules);

$model2 = new Model;
$hydrator->hydrateModel($dto, $model2, $rules);

$hydratorService = new HydratorService;
$rules = [
    'id' => [], // prop as dto`s key
    'login' => [
        'prop' => 'name', // dto key login fill property name
    ],
    'email' => [
        'set' => 'setEmail', // setter $model->setEmail();
    ]
];
$rules = $normalizer->normalize($rules);

$dto = $hydratorService->extract($model, $rules);
$model = $hydratorService->hydrate($dto, Model::class, $rules);