PHP code example of nettrine / hydrator

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

    

nettrine / hydrator example snippets


$entity = $hydrator->toFields(Entity::class, [
	'name' => 'foo',
	'field' => 'value',
]);

$entity = $hydrator->toFields($entityObj, [
	'name' => 'foo',
	'field' => 'value',
]);

$array = $hydrator->toArray($entity);

class CustomPropertyAccessor implements IPropertyAccessor {
	
	public function get(object $object, string $property) { ... }
	
	public function set(object $object, string $property, $value): void { ... }
	
}

$entity = new Assoc class {
	public $id = 42;
	
	public $foo = 'foo';
	
	/**
	 * @ManyToOne(targetEntity="Assoc")
	 */
	public $assoc;
};

$entity->assoc->id++;

$array = $hydrator->toArray($entity);

$array === [
	'id' => 42,
	'assoc' => 43,
];

$entity = new Assoc class {
	public $id = 42;
	
	public $foo = 'foo';
	
	/**
	 * @ManyToOne(targetEntity="Assoc")
	 */
	public $assoc;
};

$entity->assoc->id++;

$array = $hydrator->toArray($entity, [
	'joins' => [
		'assoc' => 'foo'
	]
]);

$array === [
	'id' => 42,
	'assoc' => 'foo',
];

$hydrator->toFields($obj, [
	'name' => 'foo',
], [
	'callbacks' => [
		'name' => function (FieldArgs $args) {
		    $args->value = ucfirst($args->value);
		},
	] 
]);

$hydrator->toFields($obj, [
	'assoc' => 42, // Item with the value of 42 will be found
]);

/**
 * @ORM\Column(type="image")
 */


class CustomFieldAdapter implements IFieldAdapter {

	public function __construct(IImageStorage $storage) { ... }

	public function isWorkable(FieldArgs $args): bool {
		// Apply only when the type is `image` and it is not an assocation
		return !$args->metadata->isAssociation($field) && $args->metadata->getFieldMapping($field)['type'] === 'image';
	}

	public function work(FieldArgs $args): void {
		$image = new Image($value);
		if ($args->hasSettingsSection('images')) {
			$image->setName($args->getSettingsSection('images'));
		}
		$this->storage->save($image);
		
		$args->value = $image;
	}

}


$hydrator->toFields($obj, [
	'avatar' => __DIR__ . '/avatar.png',
], [
	'images' => [
		'avatar' => 'foo.png',
	]
]);