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(); | |
} |
コンストラクタのないクラスでFatal Errorの不具合を修正。
__construct()未定義クラスの場合、ReflectionClass::getConstructor() は NULL を返す
$options引数のtypo発見をunset()で実装した。
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$options引数が空の場合はそのまま生成するように。
$options引数のtypoを見つけたら例外スローしたいけど綺麗に書けない…。