background image

"PersonModule"=>

array

('person'=>'bob'),

"FtpModule"=>

array

('host'=>'example.com','user'=>'anon')

);

private

 

$modules

=

array

();

function

 init(){

$interface

=

new

 ReflectionClass('Module');

foreach

(

$this

->configData 

as

 

$modulename

=>

$params

){

$module_class

=

new

 ReflectionClass(

$modulename

);

//根据配置 configData 的名称,实例化

ReflectionClass
if

(!

$module_class

->isSubclassOf(

$interface

)){

//检查反射得到了类是否是$interface 的子类

throw

 

new

 Exception("unknown module type:$modulename");

//不是 Module 子类则抛出异常

}

$module

=

$module_class

->newInstance();

//实例化一个 FtpModule 或者 PersonModule 对象

foreach

(

$module_class

->getMethods() 

as

 

$method

){

//获得类中的方法

$this

->handleMethod(

$module

,

$method

,

$params

);

}

array_push

(

$this

->modules,

$module

);

//将实例化的 module 对象放入$modules 数组中

}
}

function

 handleMethod(Module 

$module

,ReflectionMethod 

$method

,

$params

){

$name

=

$method

->getName();

//获得方法名称

$args

=

$method

->getParameters();

//获得方法中的参数

if

(

count

(

$args

)!=1||

substr

(

$name

,0,3)!="set"){

//检查方法必须是以 set 开头,且只有一个参数

return

 false;

}

$property

=

strtolower

(

substr

(

$name

,3));

//讲方法名去掉 set 三个字母,作为参数

if

(!isset(

$params

[

$property

])){

//如果$params 数组不包含某个属性,就返回 false

return

 false;

}

$arg_class

=@

$args

[0]->getClass;

//检查 setter 方法的第一个参数(且唯一)的数据类型

if

(

empty

(

$arg_class

)){

$method

->invoke(

$module

,

$params

[

$property

]);

}

else

{

$method

->invoke(

$module

,

$arg_class

->newInstance(

$params

[

$property

]));

}
}
}

$test

=

new

 ModuleRunner();

$test

->init();