PHP code example of martinezdelariva / hydrator

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

    

martinezdelariva / hydrator example snippets


    class Person
    {
        private $name;
        private $age;
        private $hobbies = [];
        private $student = false;
    
        public function __construct(string $name, int $age, array $hobbies, bool $student)
        {
            $this->name     = $name;
            $this->age      = $age;
            $this->hobbies  = $hobbies;
            $this->student  = $student;
        }
    }

    use function Martinezdelariva\Hydrator\extract;

    $person = new Person("John", 29, ["soccer", "reading"], true);
    extract($person);
   
    // array (
    //   'name'    => 'John',
    //   'age'     => 29,
    //   'hobbies' => array (
    //       0 => 'soccer',
    //       1 => 'reading',
    //   ),
    //   'student' => true,
    // )

    use function Martinezdelariva\Hydrator\hydrate;
    
    $values = [
        "name"    => "Maria",
        "age"     => 30,
        "hobbies" => ["swimming", "coding"],
    ];
    $person = hydrate(Person::class, $values);

    // object(Person)#48 (4) {
    //   ["name":"Person":private] => string(5) "Maria"
    //   ["age":"Person":private]  => int(30)
    //   ["hobbies":Person":private]=>
    //       array(2) {
    //         [0]=>
    //         string(8) "swimming"
    //         [1]=>
    //         string(6) "coding"
    //       }
    //   ["student":"Person":private] => bool(false)