当前位置: 移动技术网 > IT编程>开发语言>PHP > thinkphp控制器调度使用示例

thinkphp控制器调度使用示例

2019年03月30日  | 移动技术网IT编程  | 我要评论

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

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

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

reflectionclass主要用的方法: 
hasmethod(string)  是否存在某个方法
getmethod(string)   获取方法

reflectionmethod 主要方法: 
getnumberofparameters()  获取参数个数
getparamters()  获取参数信息

3.代码演示

复制代码 代码如下:

<?php 
class indexaction{
 public function index(){
   echo 'index'."\r\n";
 }
 public function test($year=2012,$month=2,$day=21){
   echo $year.'--------'.$month.'-----------'.$day."\r\n";
 }
 public function _before_index(){
   echo __function__."\r\n";
 }
 public function _after_index(){
   echo __function__."\r\n";
 }
}

//执行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!';

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网