Created
July 27, 2021 08:04
-
-
Save elishaukpong/0a96fb7b17727080d0da4721510372c0 to your computer and use it in GitHub Desktop.
This makes a demonstration of the PHP Reflection API
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 Person{ | |
public $name; | |
public function __construct(string $name){ | |
$this->name = $name; | |
} | |
} | |
interface Module | |
{ | |
public function execute(); | |
} | |
class FtpModule implements Module | |
{ | |
public function setHost($host) | |
{ | |
print "FtpModule::setHost(): $host\n"; | |
} | |
public function setUser($user) | |
{ | |
print "FtpModule::setUser(): $user\n"; | |
} | |
public function execute() | |
{ | |
} | |
} | |
class PersonModule implements Module | |
{ | |
public function setPerson(Person $person) | |
{ | |
print "PersonModule::setPerson(): {$person->name}\n"; | |
} | |
public function execute() | |
{ | |
} | |
} | |
class ModuleRunner | |
{ | |
private $configData = [ | |
PersonModule::class => ['person' => 'bob'], | |
FtpModule::class => [ | |
'host' => 'example.com', | |
'user' => 'anon' | |
] | |
]; | |
private $modules = []; | |
public function init() | |
{ | |
$interface = new \ReflectionClass(Module::class); | |
foreach ($this->configData as $moduleName => $params) | |
{ | |
$moduleClass = new \ReflectionClass($moduleName); | |
if(! $moduleClass->isSubclassOf($interface)){ | |
throw new Exception("unknown module type: $moduleName"); | |
} | |
$module = $moduleClass->newInstance(); | |
foreach($moduleClass->getMethods() as $method) | |
{ | |
$this->handle($module, $method, $params); | |
} | |
array_push($this->modules,$module); | |
} | |
} | |
public function handle(Module $module, ReflectionMethod $method, array $params) | |
{ | |
$name = $method->getName(); | |
$args = $method->getParameters(); | |
if(count($args) != 1 || substr($name,0,3) != "set"){ | |
return false; | |
} | |
$property = strtolower(substr($name,3)); | |
if(! isset($params[$property])){ | |
return false; | |
} | |
$argClass = $args[0]->getClass(); | |
if(empty($argClass)){ | |
$method->invoke($module, $params[$property]); | |
}else{ | |
$method->invoke( | |
$module, | |
$argClass->newInstance($params[$property]) | |
); | |
} | |
} | |
} | |
$init = new ModuleRunner(); | |
$init->init(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment