Skip to content

Instantly share code, notes, and snippets.

@AoJ
Created October 30, 2011 21:52
Show Gist options
  • Save AoJ/1326496 to your computer and use it in GitHub Desktop.
Save AoJ/1326496 to your computer and use it in GitHub Desktop.
class instance factory
<?php
$new_ = new new_;
echo $new_::Test('I', 'live', '!')->get();
echo $new_::NonExistsClass('I', "don't", 'live', '!')->get();
echo (string)$new_::NonExistsClass('I', "don't", 'live', '!');
$class = $new_::NonExistsClass('I', "don't", 'live', '!');
$class::test();
$class();
class Test {
private $text;
function __construct() {
$this->text = implode(' ', func_get_args());
}
function get() { return $this->text; }
}
<?php
/**
* Created by bored programmer
* useful as stupid factory for instance class with smart logging and error protecting
* User: AoJ
*
* example
* $new_ = new new_
* $new_::Test('I', 'live', '!')->get(); //I live !
* $new_::NonExistsClass('I', "don't", 'live', '!')->get(); //[sandbox]
*
* you can implement sandbox class for logging and managing errors and wrong calls
*/
class new_ implements INew_ {
private static $sandbox;
public function __construct(NewSandbox $sandbox = null) {
$sandbox || $sandbox = new NewSandbox;
self::$sandbox = $sandbox;
}
public static function __callStatic($class, $arguments = array()) {
return self::factory($class, $arguments);
}
protected static function factory($class, $arguments = array()) {
$instance = false;
$exception = null;
try {
$classReflection = new ReflectionClass($class);
$instance = $classReflection->newInstanceArgs($arguments);
}
//class is not instantiable
catch(ReflectionException $e) { $exception = $e; }
//class' construct throwed exception, ehm, isn't my exception, I don't worry about it, get out!
catch(Exception $e) { $exception = null; throw $e; }
//this check cost 15% of time to create instance
if(is_object($instance) && $instance instanceof $class) return $instance;
return self::$sandbox->dummy($class, $arguments, $exception);
}
}
interface INew_ {
static function __callStatic($class, $arguments);
}
class NewSandbox {
public static function __callStatic($name, $arguments) { }
public function __call($name, $arguments) { return $this; }
public function __toString() { return ''; }
public function __invoke() { }
public function dummy($class, $args, $e = null) { return $this; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment