首页 > 开发 > ThinkPHP > 正文

thinkphp控制器调度使用示例

2020-10-12 20:55:12
字体:
来源:转载
供稿:网友

这篇文章主要介绍了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. //执行index方法 
  17. $method = new ReflectionMethod('IndexAction','index'); 
  18. //进行权限判断 
  19. if($method->isPublic()){ 
  20.  $class = new ReflectionClass('IndexAction'); 
  21.  //执行前置方法 
  22.  if($class->hasMethod('_before_index')){ 
  23.   $beforeMethod = $class->getMethod('_before_index'); 
  24.   if($beforeMethod->isPublic()){ 
  25.    $beforeMethod->invoke(new IndexAction); 
  26.   } 
  27.  } 
  28.  
  29.  $method->invoke(new IndexAction); 
  30.  
  31.  //执行后置方法 
  32.  if($class->hasMethod('_after_index')){ 
  33.   $beforeMethod = $class->getMethod('_after_index'); 
  34.   if($beforeMethod->isPublic()){ 
  35.    $beforeMethod->invoke(new IndexAction); 
  36.   } 
  37.  } 
  38.  
  39.  
  40. //执行带参数的方法 
  41. $method = new ReflectionMethod('IndexAction','test'); 
  42. $params = $method->getParameters(); 
  43. foreach($params as $param ){ 
  44.  $paramName = $param->getName(); 
  45.  if(isset($_REQUEST[$paramName])) 
  46.   $args[] = $_REQUEST[$paramName]; 
  47.  elseif($param->isDefaultValueAvailable()) 
  48.   $args[] = $param->getDefaultValue(); 
  49. if(count($args)==$method->getNumberOfParameters()) 
  50.  $method->invokeArgs(new IndexAction,$args); 
  51. else 
  52.  echo 'parameters is not match!'

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选