PHP code example of solodkiy / doctrine-array-hydrator

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

    

solodkiy / doctrine-array-hydrator example snippets




namespace App\Entity;
    
use Doctrine\ORM\Mapping as ORM;
use Solodkiy\Doctrine\Hydrator\Test\Fixture\Company;
use Solodkiy\Doctrine\Hydrator\Test\Fixture\Permission;

/**
 * @ORM\Entity
 * @ORM\Table(name="users")
 */
class User
{
   /**
    * @ORM\Id 
    * @ORM\Column(type="integer") 
    * @ORM\GeneratedValue
    * 
    * @var int
    */
    protected $id;
    
    /**
     * @ORM\Column(type="string")
     * 
     * @var string
     */
    protected $name;
    
    /**
     * @ORM\Column(type="string")
     * 
     * @var string
     */
    protected $email;
    
    /**
     * @ManyToOne(targetEntity="Company")
     * 
     * @var Company
     */
    protected $company;
        
    /**
     * @OneToMany(targetEntity="Permission", mappedBy="product")
     * 
     * @var Permission[]
     */
    protected $permissions;
}

$data = [
    'name'        => 'Fred Jones',
    'email'       => '[email protected]',
    'company'     => 2,
    'permissions' => [1, 2, 3, 4]
];

$hydrator = new \Solodkiy\Doctrine\Hydrator\ArrayHydrator($entityManager);
$entity   = $hydrator->hydrate('App\Entity\User', $data);

$data = [
    'attributes'    => [
        'name'  => 'Fred Jones',
        'email' => '[email protected]',
    ],
    'relationships' => [
        'company'     => [
            'data' => ['id' => 1, 'type' => 'company'],
        ],
        'permissions' => [
            'data' => [
                ['id' => 1, 'type' => 'permission'],
                ['id' => 2, 'type' => 'permission'],
                ['id' => 3, 'type' => 'permission'],
                ['id' => 4, 'type' => 'permission'],
                ['name' => 'New permission']
            ]
        ]
    ]
];
    
$hydrator = new \Solodkiy\Doctrine\Hydrator\JsonApiHydrator($entityManager);
$entity   = $hydrator->hydrate('App\Entity\User', $data);