当前位置:首页 > CMS教程 > Thinkphp > 列表

thinkphp控制器调度使用示例

发布:smiling 来源: PHP粉丝网  添加日期:2020-09-17 15:15:27 浏览: 评论:0 

这篇文章主要介绍了thinkphp控制器调度使用示例,需要的朋友可以参考下

1.如何通过地址栏参数来得到模块名称和控制器名称(即使在有路由和开了重写模块的情况下)

2.tp是如何实现前置,后置方法功能模块,和如何执行带参数的方法?

php系统自带的 ReflectionClass,ReflectionMethod 类,可以反射用户自定义类的中属性,方法的权限和参数等信息,通过这些信息可以准确的控制方法的执行

ReflectionClass主要用的方法: 

hasMethod(string)  是否存在某个方法

getMethod(string)   获取方法

ReflectionMethod 主要方法: 

getNumberOfParameters()  获取参数个数

getParamters()  获取参数信息

3.代码演示:

  1. <?php  
  2. class IndexAction{ 
  3.  public function index(){ 
  4.    echo 'index'."\r\n"; 
  5.  } 
  6.  public function test($year=2012,$month=2,$day=21){ 
  7.    echo $year.'--------'.$month.'-----------'.$day."\r\n"; 
  8.  } 
  9.  public function _before_index(){ 
  10.    echo __FUNCTION__."\r\n"; 
  11.  } 
  12.  public function _after_index(){ 
  13.    echo __FUNCTION__."\r\n"; 
  14.  } 
  15. } 
  16.  
  17. //执行index方法 
  18. $method = new ReflectionMethod('IndexAction','index'); 
  19. //进行权限判断 
  20. if($method->isPublic()){ 
  21.  $class = new ReflectionClass('IndexAction'); 
  22.  //执行前置方法 
  23.  if($class->hasMethod('_before_index')){ 
  24.   $beforeMethod = $class->getMethod('_before_index'); 
  25.   if($beforeMethod->isPublic()){ 
  26.    $beforeMethod->invoke(new IndexAction); 
  27.   } 
  28.  } 
  29.  
  30.  $method->invoke(new IndexAction); 
  31.  
  32.  //执行后置方法 
  33.  if($class->hasMethod('_after_index')){ 
  34.   $beforeMethod = $class->getMethod('_after_index'); 
  35.   if($beforeMethod->isPublic()){ 
  36.    $beforeMethod->invoke(new IndexAction); 
  37.   } 
  38.  } 
  39. } 
  40.  
  41.  
  42. //执行带参数的方法 
  43. $method = new ReflectionMethod('IndexAction','test'); 
  44. $params = $method->getParameters(); 
  45. foreach($params as $param ){ 
  46.  $paramName = $param->getName(); 
  47.  if(isset($_REQUEST[$paramName])) 
  48.   $args[] = $_REQUEST[$paramName]; 
  49.  elseif($param->isDefaultValueAvailable()) 
  50.   $args[] = $param->getDefaultValue(); 
  51. } 
  52. if(count($args)==$method->getNumberOfParameters()) 
  53.  $method->invokeArgs(new IndexAction,$args); 
  54. else 
  55.  echo 'parameters is not match!'; 

Tags: thinkphp控制器调度

分享到: