Last active
December 29, 2015 01:49
-
-
Save k-holy/7595487 to your computer and use it in GitHub Desktop.
ReflectionClassを使ったファクトリ
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 | |
function factory($class, array $options = array()) | |
{ | |
if (count($options) === 0) { | |
return new $class(); | |
} | |
$refClass = new \ReflectionClass($class); | |
$constructor = $refClass->getConstructor(); | |
$arguments = array(); | |
if ($constructor instanceof \ReflectionMethod) { | |
foreach ($constructor->getParameters() as $param) { | |
$paramName = $param->getName(); | |
if (array_key_exists($paramName, $options)) { | |
$arguments[] = $options[$paramName]; | |
unset($options[$paramName]); | |
} else { | |
$arguments[] = $param->getDefaultValue(); | |
} | |
} | |
} | |
if (count($options) !== 0) { | |
throw new \InvalidArgumentException( | |
sprintf('Not supported parameter [%s]', implode(',', array_keys($options))) | |
); | |
} | |
return (count($arguments) >= 1) | |
? $refClass->newInstanceArgs($arguments) | |
: $refClass->newInstance(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$options引数のtypo発見をunset()で実装した。