Created
April 16, 2015 15:17
-
-
Save brandonhesse/e21eba1554f8c4a6fa3d to your computer and use it in GitHub Desktop.
Sample of what modular serializer might look like
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 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