每日学习笔记(11)
时间:2010-09-30 来源:Phinecos(洞庭散人)
1,php中反射API应用的一个实例
代码 <?phpclass Person
{
public $name;
function __construct($name)
{
$this->name = $name;
}
}
interface IModule
{
function execute();
}
class FtpModule implements IModule
{
function execute()
{
}
function setHost($host)
{
print "FtpModule::setHost: {$host}\n";
}
function setUser($user)
{
print "FtpModule::setUser: {$user}\n";
}
}
class PersonModule implements IModule
{
function execute()
{
}
function setPerson(Person $person)
{
print "PersonModule::setPerson: {$person->name}\n";
}
}
class ModuleRunner
{
private $configData = array("PersonModule" => array('person'=>'bob'),
"FtpModule" => array('host' => 'google.com','user' => 'phinecos')
);
private $modules = array();
function init()
{
$interface = new ReflectionClass('IModule');
foreach( $this->configData as $moduleName => $params) {
$module_class = new ReflectionClass($moduleName);
if ( !$module_class -> isSubclassOf($interface) ) {
throw new Exception("unknown module: $moduleName");
}
$module = $module_class->newInstance();
foreach( $module_class->getMethods() as $method) {
$this->handleMethod($module, $method, $params);
}
array_push($this->modules, $module);
}
}
function handleMethod(IModule $module, ReflectionMethod $method, $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;
}
$arg_class = $args[0]->getClass();
if ( empty($arg_class)) {
$method->invoke($module, $params[$property]);
} else {
$method->invoke($module, $arg_class->newInstance($params[$property]));
}
}
}
$test = new ModuleRunner();
$test->init();
?>
相关阅读 更多 +