- property_exists: documentation ( source)
- var_dump: documentation ( source)
- sprintf: documentation ( source)
<?php
$config = ['legendaryName' => 'legendary_name'];
$data = ['legendary_name' => 'The Hammer'];
class Warrior {
use DbHydrate;
private $legendaryName;
}
trait DbHydrate {
public function extract($config)
{
$row = [];
foreach($config as $attributeName => $column)
{
if(property_exists($this, $attributeName)) {
$row[$column] = $this->{$attributeName};
} else {
throw new \Exception(sprintf('The property %s does not exists in %s', $attributeName, self::class));
}
}
return $row;
}
public function hydrate($config, $data)
{
foreach($config as $attributeName => $column)
{
if(property_exists($this, $attributeName)) {
$this->{$attributeName} = $data[$column];
} else {
throw new \Exception(sprintf('The property %s does not exists in %s', $attributeName, self::class));
}
}
}
}
$legendaryWarrior = new Warrior;
$legendaryWarrior->hydrate($config, $data);
var_dump($legendaryWarrior->extract($config));
var_dump($legendaryWarrior);
/*
$config = ['classicalName' => 'classical_name'];
$data = ['classical_name' => 'John'];
$testWarrior = new Warrior;
$testWarrior->hydrate($config, $data);
var_dump($testWarrior);*/