Skip to content

Instantly share code, notes, and snippets.

@adamlundrigan
Last active August 29, 2015 14:14
Show Gist options
  • Save adamlundrigan/4f74d88492106c692fc6 to your computer and use it in GitHub Desktop.
Save adamlundrigan/4f74d88492106c692fc6 to your computer and use it in GitHub Desktop.
<?php
<<<CONFIG
packages:
- "zendframework/zendframework:~2.3"
CONFIG;
class Weather {
private $time;
private $rain;
function setTime($time) {
$this->time = $time;
}
function getTime() {
return $this->time;
}
function setRain(Rain $rain) {
$this->rain = $rain;
}
function getRain() {
return $this->rain;
}
}
class Rain {
private $description;
function setDescription($description) {
$this->description = $description;
}
function getDescription() {
return $this->description;
}
}
class HydratorStrategy implements Zend\Stdlib\Hydrator\Strategy\StrategyInterface
{
private $hydrator;
private $className;
public function __construct(Zend\Stdlib\Hydrator\HydratorInterface $hydrator, $className)
{
$this->hydrator = $hydrator;
$this->className = $className;
}
public function extract($value)
{
return $this->hydrator->extract($value);
}
public function hydrate($value)
{
$object = new $this->className;
return $this->hydrator->hydrate($value, $object);
}
}
$rainHydrator = new Zend\Stdlib\Hydrator\ClassMethods(false);
$weatherHydrator = new Zend\Stdlib\Hydrator\ClassMethods(false);
$weatherHydrator->addStrategy('rain', new HydratorStrategy($rainHydrator, Rain::class));
$myWeatherObject = new Weather();
$myWeatherData = [
'time' => '12:22',
'rain' => [
'description' => 'test'
]
];
var_dump($weatherHydrator->hydrate($myWeatherData, $myWeatherObject));
var_dump($weatherHydrator->extract($myWeatherObject));
adam@adampc:/tmp$ melody run hydrators.php
class Weather#24 (2) {
private $time =>
string(5) "12:22"
private $rain =>
class Rain#25 (1) {
private $description =>
string(4) "test"
}
}
array(2) {
'time' =>
string(5) "12:22"
'rain' =>
array(1) {
'description' =>
string(4) "test"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment