PHP code example of ngexp / hydrator

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

    

ngexp / hydrator example snippets




declare(strict_types = 1);

dapter;
use Ngexp\Hydrator\Asserts as Assert;
use Ngexp\Hydrator\Hydrator;
use Ngexp\Hydrator\HydratorException;

// The data we want to hydrate the instance with.
$json = <<<JSON
{
  "name": "John Doe",
  "age": 20,
  "unrelated": "data"
}
JSON;

// The class has the same data structure as the json data.
class User
{
  public string $name;
  #[Assert\Min(30)]
  public int $age;
}

try {
  // We create a new instance of the class by specifying its class name.
  $hydrator = new Hydrator(User::class);
  // Hydrate using the json adapter.
  $class = $hydrator->hydrate(new JsonAdapter($json));

  var_dump($class);

} catch (HydratorException $e) {
  echo $e->getMessage();
}

#[AutoCast]
private int $age;

#[CoerceInt]
private int $age;

class User
{
  public function __construct(public string $name, #[CoerceInt] public int $age)
  {
  }
}

#[Email(message="Custom error message", errorCode="unique_error_code")]
private string $email;

$class = $hydrator->hydrate(new JsonAdapter($json));

$class = $hydrator->hydrate(new ArrayAdapter($array));