prolic/humus-doctrine-hydrator

此包已被废弃,不再维护。未建议替代包。

Humus Doctrine(递归)Hydrator

1.1.0 2013-07-07 11:33 UTC

This package is auto-updated.

Last update: 2020-03-09 18:07:25 UTC


README

Humus Doctrine Hydrator

Dependency Status Total Downloads Latest Stable Version Latest Unstable Version

实现 Zend\Stdlib\Hydrator\HydratorInterface 的 Hydrator,完全基于 Doctrine\Common

  • 可以返回克隆的对象
  • 可以控制哪些字段应该被提取(递归地)
  • 可以将单个键扁平化

要求

安装

  1. "prolic/humus-doctrine-hydrator": "dev-master" 添加到您的 composer.json
  2. 运行 php composer.phar install

示例

假设您想将一个数组注入到一个对象中,然后提取它的所有内部结构

示例类:"User",与他的 "Locale","Language" 和 "Address" 有关系。地址实体也与 "Country" 有关系。

$hydrator = new \Humus\Doctrine\Hydrator\Hydrator(
    $context->get('EntityManager'), // the entity manager
    true, // yes, we want a cloned object, not the original one
    array(
        'id',
        'name',
        'firstname',
        'fax',
        'email',
        'gender',
        'locale' => array(
            'name'
        ),
        'preferred_contact_type' => array(
            'id'
        ),
        'address' => array(
            'street',
            'zip',
            'city',
            'country' => array(
                'id',
                'name'
            ),
        ),
        'spoken_languages' => array(
            'id',
        ),
    ), // we describe, what should be returned by extract, otherwise it could be that
       // a) We dump the Unit of Work
       // b) We dump half of the database
    false //do not flat single keys
);

// we got some data
$data = array(
    'id' => 5,
);

// we get the cloned address object,
// just switch the clone argument in constructor to false, in order to get the real object back
$address = $hydrator->hydrate($data, new \Application\Entity\Contact());

$result = $hydrator->extract($address);
var_dump($result);

// output:
array(6) {
  ["id"]=>
  int(5)
  ["gender"]=>
  string(4) "male"
  ["name"]=>
  string(20) "Sascha-Oliver Prolic"
  ["locale"]=>
  array(1) {
    ["name"]=>
    string(10) "Deutsch DE"
  }
  ["address"]=>
  array(4) {
    ["street"]=>
    string(13) "Sample Street"
    ["zip"]=>
    string(5) "00000"
    ["city"]=>
    string(6) "Berlin"
    ["country"]=>
    array(2) {
      ["id"]=>
      int(1)
      ["name"]=>
      string(7) "Germany"
    }
  }
  ["spoken_languages"]=>
  array(1) {
    [0]=>
    array(1) {
      ["id"]=>
      int(1)
    }
  }
}

// Please note how the output changes (watch for locale) when you switch the "flatSingleKeys" flag to true
// in the constructor of the hydrator