fenric/doctrine-array-hydrator

Doctrine 2 实体数组的实体 hydrator(分支版)

v0.1.8 2020-02-11 07:40 UTC

This package is auto-updated.

Last update: 2024-09-11 18:02:24 UTC


README

介绍

Build Status Test Coverage Downloads

Doctrine 2 的 hydrator,可以将数组转换为您的选择实体。

通过 Composer 安装

推荐的安装方法是使用 Composer

composer require pmill/doctrine-array-hydrator

示例

给定这个 Doctrine 实体

<?php

namespace App\Entity;
    
use Doctrine\ORM\Mapping as ORM;
use pmill\Doctrine\Hydrator\Test\Fixture\Company;
use pmill\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'       => 'fred@example.com',
    'company'     => 2,
    'permissions' => [1, 2, 3, 4]
];

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

我们可以用 JSON API 资源数据填充用户 文档

$data = [
    'attributes'    => [
        'name'  => 'Fred Jones',
        'email' => 'fred@example.com',
    ],
    '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 \pmill\Doctrine\Hydrator\JsonApiHydrator($entityManager);
$entity   = $hydrator->hydrate('App\Entity\User', $data);

版权

Doctrine 数组到实体 hydrator 版权 (c) 2015 pmill (dev.pmill@gmail.com) 所有权利保留。