Skip to content

Instantly share code, notes, and snippets.

@brandonhesse
Created April 16, 2015 15:17
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 brandonhesse/e21eba1554f8c4a6fa3d to your computer and use it in GitHub Desktop.
Save brandonhesse/e21eba1554f8c4a6fa3d to your computer and use it in GitHub Desktop.
Sample of what modular serializer might look like
<?php
interface DecoratorInterface {
public function dectorate($value, array $options);
public function supports($class);
}
class InvalidDecoratorSerilizationException extends \Exception {};
class DateTimeDecorator impliments DecoratorInterface {
public fuction decorate($value, array $options) {
// Do something wih options
if ($this->supports($value)) {
return $value->format('c') . 'Z';
}
throw new InvalidDecoratorSerilizationException('Was unable to seri');
}
public function supports($class) {
return $class instanceof \DateTime || is_subclass_of($class, \DateTime);
}
}
class MarcoSerializer {
private $availableDecorators = array();
public __construct(array $decorators = array()) {
$this->availableDecorators = array_merge($this->availableDecorators, $decorators);
}
public serialize($obj) {
$serialized = array();
foreach($obj as $key => $value) {
// Key will be int for array.
// ... do checks and balances
$decorated = null;
foreach($this->availableDecorators as $key => $decorator) {
if ($decorator->supports($value)) {
$decorated = $decorator->decorate($value);
} else if ($value instanceof \Serializable) {
$decorated = $value->serialize();
} else {
// Do fallback
}
}
array_push($serialized, $decorated);
}
return json_encode($serialized);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment