NotionCommotion Posted November 28, 2017 Share Posted November 28, 2017 Is this a bad idea? It works, but that doesn't mean it is a good idea. If not a bad idea, is it possible to implement using the alias class name ($router->getObj('Controllers\Test1')->getSomething();)? Ideally, the script to deal with the alias would be in Router and not the first file. <?php use Michael\SimpleRouter; use Michael\EmbeddedWebserver\Controllers; spl_autoload_register(function ($class) { $prefix = 'Michael\\'; $base_dir = __DIR__ . '/../src/'; $len = strlen($prefix); if (strncmp($prefix, $class, $len) !== 0) return; $relative_class = substr($class, $len); $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php'; if (file_exists($file)) require $file; }); $router = new SimpleRouter\Router(); $test1=$router->getObj('Michael\EmbeddedWebserver\Controllers\Test1')->getSomething(); $test2=$router->getObj('Michael\EmbeddedWebserver\Controllers\Test2',1,2,3)->getSomething(); <?php namespace Michael\SimpleRouter; class Router implements RouterInterface { public function getObj($class) { $args=func_get_args(); unset($args[0]); $o = new \ReflectionClass($class); return $args?$o->newInstanceArgs($args):$o->newInstanceArgs($args); } public function otherMethodsAsAppropriate(); } <?php namespace Michael\EmbeddedWebserver\Controllers; class Test1 { public function getSomething() { return 10; } } <?php namespace Michael\EmbeddedWebserver\Controllers; class Test2 { public function __construct($one, $two, $three) { $this->one=$one; $this->two=$two; $this->three=$three; } public function getSomething() { return 10*$this->one*$this->two*$this->three; } } Quote Link to comment Share on other sites More sharing options...
kicken Posted November 28, 2017 Share Posted November 28, 2017 You could construct an object that way, sure. I don't really see the point in doing it that way though. You'd probably have a hard time convincing me that such a thing is worth doing vs just constructing your objects normally. Reflection is generally slow, so best to be avoided. Hiding your class names as strings will also break many IDE features such as refactoring, finding usages, etc. I don't see much reason to try and alias your classes. With a good IDE and decent naming referencing the actual class shouldn't be a problem. Autocomplete + Automatic use importing makes just doing new Test() a snap. Quote Link to comment Share on other sites More sharing options...
NotionCommotion Posted November 28, 2017 Author Share Posted November 28, 2017 Thanks kicken, Enough said! I will stick to the tried and true. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.