ThinkPHP控制器调度与反射机制详解
1.探讨如何通过地址栏参数提取模块名称与控制器名称(即便在启用路由或重写模块功能时)
2.ThinkPHP如何实现前置与后置方法的功能模块,以及如何执行带有参数的方法?
PHP系统内置的 ReflectionClass 和 ReflectionMethod 类能够反射用户自定义类中的属性、方法权限及参数等详细信息,借助这些反射信息,可以精确地控制方法的执行流程。
ReflectionClass 类主要使用的方法包括: hasMethod(string) 用于判断是否存在指定名称的方法 getMethod(string) 用于获取指定的方法对象
ReflectionMethod 类主要使用的方法包括: getNumberOfParameters() 用于获取方法的参数个数 getParameters() 用于获取详细的参数信息
3.代码演示
复制代码 代码如下:
//执行index方法 $method = new ReflectionMethod('IndexAction','index'); //进行权限判断 if($method->isPublic()){ $class = new ReflectionClass('IndexAction'); //执行前置方法 if($class->hasMethod('_before_index')){ $beforeMethod = $class->getMethod('_before_index'); if($beforeMethod->isPublic()){ $beforeMethod->invoke(new IndexAction); } }
$method->invoke(new IndexAction);
//执行后置方法 if($class->hasMethod('_after_index')){ $beforeMethod = $class->getMethod('_after_index'); if($beforeMethod->isPublic()){ $beforeMethod->invoke(new IndexAction); } } }
//执行带参数的方法 $method = new ReflectionMethod('IndexAction','test'); $params = $method->getParameters(); foreach($params as $param ){ $paramName = $param->getName(); if(isset($_REQUEST[$paramName])) $args[] = $_REQUEST[$paramName]; elseif($param->isDefaultValueAvailable()) $args[] = $param->getDefaultValue(); } if(count($args)==$method->getNumberOfParameters()) $method->invokeArgs(new IndexAction,$args); else echo 'parameters is not match!';