Skip to content

Instantly share code, notes, and snippets.

@brzuchal
Last active August 18, 2016 10:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brzuchal/b7bb5caa67cb0db088daed1982a6a644 to your computer and use it in GitHub Desktop.
Save brzuchal/b7bb5caa67cb0db088daed1982a6a644 to your computer and use it in GitHub Desktop.
Hydrator example with object type-hint and return-type
<?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'));
<?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