Created
February 21, 2013 05:13
-
-
Save estahn/5002290 to your computer and use it in GitHub Desktop.
Our current framework is heavily using a "Factory" to instantiate classes on the fly. It used ReflectionClass::newInstanceArgs() for classes with arguments. Since Reflection is quite slow it decreased our performance. The gist shows a solution that is less beautiful but more performant.
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 | |
class Factory | |
{ | |
// ... | |
/** | |
* Helper to instantiate objects with dynamic constructors. | |
* | |
* The beautiful way: | |
* <code> | |
* $reflection = new ReflectionClass($classNameNormalized); | |
* return $reflection->newInstanceArgs($arguments); | |
* </code> | |
* | |
* Reflection->newInstanceArgs() is very slow and therefore replaced | |
* by generated PHP code which is executed with eval. | |
* | |
* @param string $class | |
* @param array $arguments | |
* @return mixed | |
*/ | |
public static function createInstance($class, $arguments = null) | |
{ | |
if (is_null($arguments)) { | |
return new $class; | |
} | |
$instance = null; | |
$codeScaffold = '$instance = new %s(%s);'; | |
$codeArguments = array(); | |
foreach ($arguments as $index => $argument) { | |
${'arg' . $index} = $argument; | |
$codeArguments[] = '$arg' . $index; | |
} | |
eval(sprintf($codeScaffold, $class, implode(', ', $codeArguments))); | |
return $instance; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment