1. Go to this page and download the library: Download symplify/easy-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/ */
namespace App\ValueObject;
use DateTimeInterface;
final class Person
{
private string $name;
private int $age;
private DateTimeInterface $metAt;
public function __construct(string $name, int $age, DateTimeInterface $metAt)
{
$this->name = $name;
$this->age = $age;
$this->metAt = $metAt;
}
public function getName(): string
{
return $this->name;
}
public function getAge(): int
{
return $this->age;
}
public function getMetAt(): DateTimeInterface
{
return $this->metAt;
}
}
namespace App\Repository;
use App\ValueObject\Person;
use Symplify\EasyHydrator\ArrayToValueObjectHydrator;
final class HumanRepository
{
/**
* @var ArrayToValueObjectHydrator
*/
private $arrayToValueObjectHydrator;
public function __construct(ArrayToValueObjectHydrator $arrayToValueObjectHydrator)
{
$this->arrayToValueObjectHydrator = $arrayToValueObjectHydrator;
}
public function getPerson(): Person
{
return $this->arrayToValueObjectHydrator->hydrateArray([
'name' => 'Tom',
// will be retyped to int
'age' => '30',
// will be retyped to DateTimeInterface
'metAt' => '2020-02-02',
], Person::class);
// ...
}
}
$singlePersonAsArray = [
'name' => 'Tom',
// will be retyped to int
'age' => '30',
// will be retyped to DateTimeInterface
'metAt' => '2020-02-02',
]);
/** @var Person $person */
$person = $this->arrayToValueObjectHydrator->hydrateArray($singlePersonAsArray, Person::class);
$manyPersonsAsArray = [];
$manyPersonsAsArray[] = [
'name' => 'Tom',
// will be retyped to int
'age' => '30',
// will be retyped to DateTimeInterface
'metAt' => '2020-02-02',
];
$manyPersonsAsArray[] = [
'name' => 'John',
// will be retyped to int
'age' => '25',
// will be retyped to DateTimeInterface
'metAt' => '2019-12-31',
];
/** @var Person[] $persons */
$persons = $this->arrayToValueObjectHydrator->hydrateArrays($manyPersonsAsArray, Person::class);
class MyObject
{
private string $foo;
private string $bar;
public function __construct(string $foo, string $bar = 'bar')
{
$this->foo = $foo;
$this->bar = $bar;
}
public function getFoo(): string
{
return $this->foo;
}
public function getBar(): string
{
return $this->bar;
}
}
$data = [
'foo' => 'foo',
];
$object = $this->arrayToValueObjectHydrator->hydrateArray($data, MyObject::class);
// bar
$object->getBar();
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.