-
-
Save brzuchal/b7bb5caa67cb0db088daed1982a6a644 to your computer and use it in GitHub Desktop.
Hydrator example with object type-hint and return-type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
interface ServiceContainer { | |
/** | |
* Set service definition | |
* @param string $id Service identifier | |
* @param object $service Service object or closure | |
*/ | |
public function set(string $id, object $service); | |
/** | |
* Retrieve service object from container | |
* @param string $id Service identifier | |
* @return | |
*/ | |
public function get(string $id) : object; | |
} | |
class Container implements ServiceContainer { | |
/** @var object[] */ | |
private $services = []; | |
/** | |
* {@inheritdoc} | |
*/ | |
public function set(string $id, object $service) { | |
$this->services[$id] = $service; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function get(string $id) : object { | |
// some assertion | |
$service = $this->services[$id]; | |
if ($service instanceof Closure) { | |
return $service(); | |
} | |
return $service; | |
} | |
} | |
$container = new Container(); | |
$container->set('std', new stdClass()); | |
$container->set('lazy', function () use ($container) : object { | |
return $container->get('std'); | |
}); | |
var_dump($container->get('std'), $container->get('lazy')); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
interface Hydration { | |
/** | |
* Hydrate an object by populating data | |
* @param array $data Data to populate | |
* @param object $object Object to populate data | |
* @return object | |
*/ | |
public function hydrate(array $data, object $object) : object; | |
} | |
interface Extraction { | |
/** | |
* Extract values from an object | |
* @param object $object Object to extract data from | |
* @return array | |
*/ | |
public function extract(object $object) : array; | |
} | |
class Hydrator implements Hydration, Extraction { | |
/** | |
* {@inheritdoc} | |
*/ | |
public function hydrate(array $data, object $object) : object { | |
// hydration implementation without need for `is_object` validation | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function extract(object $object) : array { | |
// extraction validation without need for `is_object` validation | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment