我有一个Validator
类,它创建一个类的实例Validations
,其中包含所有验证方法.当进行验证,__call
在Validator
使用派遣一个电话来.Validator->validate_method
Validations->method
例如,有一个Validations
被调用的方法length_of
.运行以下代码时:
$v = new Validator();
$v->validate_length_of(...);
Run Code Online (Sandbox Code Playgroud)
执行类中的length_of
验证Validations
.
为了确保__call
不会尝试调度到无效或非公共Validation
方法,我ReflectionMethod
用来检查指定的方法:
$method = new ReflectionMethod($this->validations, $validation_method);
if (!$method->isPublic())
{
// error
}
Run Code Online (Sandbox Code Playgroud)
我很确定这是确定方法是否公开的唯一方法,但我不确定Reflection是否适合生成代码.这是代码味吗?
你真的不应该在生产代码中使用Reflection.你为什么不在这里使用is_callable
?
if (!is_callable(array('Validations', $validation_method)) {
throw new LogicException('method does not exist');
}
Run Code Online (Sandbox Code Playgroud)
这将检查Validations
该类是否具有静态方法,$validation_method
并确保您可以从当前上下文中调用它.实际上,这为您提供了比反射更多的灵活性,因为这会将__call
方法和类似的东西考虑在内,而Reflection则没有.