本文实例讲述了thinkphp基于反射实现钩子的方法。分享给大家供大家参考,具体如下:
thinkphp框架的控制器模块是如何实现 前控制器、后控制器,及如何执行带参数的方法?
php系统自带的 reflectionclass、reflectionmethod 类,可以反射用户自定义类的中属性,方法的权限和参数等信息,通过这些信息可以准确的控制方法的执行。
reflectionclass:
主要用的方法:
hasmethod(string) 是否存在某个方法
getmethod(string) 获取方法
reflectionmethod:
主要方法:
ispublic() 是否为 public 方法
getnumberofparameters() 获取参数个数
getparamters() 获取参数信息
invoke( object $object [, mixed $parameter [, mixed $... ]] ) 执行方法
invokeargs(object obj, array args) 带参数执行方法
实例演示
<?php
class blogaction {
public function detail() {
echo 'detail' . "rn";
}
public function test($year = 2014, $month = 4, $day = 21) {
echo $year . '--' . $month . '--' . $day . "rn";
}
public function _before_detail() {
echo __function__ . "rn";
}
public function _after_detail() {
echo __function__ . "rn";
}
}
// 执行detail方法
$method = new reflectionmethod('blogaction', 'detail');
$instance = new blogaction();
// 进行权限判断
if ($method->ispublic()) {
$class = new reflectionclass('blogaction');
// 执行前置方法
if ($class->hasmethod('_before_detail')) {
$beforemethod = $class->getmethod('_before_detail');
if ($beforemethod->ispublic()) {
$beforemethod->invoke($instance);
}
}
$method->invoke(new blogaction);
// 执行后置方法
if ($class->hasmethod('_after_detail')) {
$beforemethod = $class->getmethod('_after_detail');
if ($beforemethod->ispublic()) {
$beforemethod->invoke($instance);
}
}
}
// 执行带参数的方法
$method = new reflectionmethod('blogaction', '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($instance, $args);
} else {
echo 'parameters is wrong!';
}
另一段代码参考
/**
* 执行app控制器
*/
public function execapp() {
// 创建action控制器实例
$classname = module_name . 'controller';
$namespaceclassname = '\apps\' . app_name . '\controller\' . $classname;
load_class($namespaceclassname, false);
if (!class_exists($namespaceclassname)) {
throw new exception('oops! module not found : ' . $namespaceclassname);
}
$controller = new $namespaceclassname();
// 获取当前操作名
$action = action_name;
// 执行当前操作
//call_user_func(array(&$controller, $action)); // 其实吧,用这个函数足够啦!!!
try {
$methodinfo = new reflectionmethod($namespaceclassname, $action);
if ($methodinfo->ispublic() && !$methodinfo->isstatic()) {
$methodinfo->invoke($controller);
} else { // 操作方法不是public类型,抛出异常
throw new reflectionexception();
}
} catch (reflectionexception $e) {
// 方法调用发生异常后,引导到__call方法处理
$methodinfo = new reflectionmethod($namespaceclassname, '__call');
$methodinfo->invokeargs($controller, array($action, ''));
}
return;
}
更多关于thinkphp相关内容感兴趣的读者可查看本站专题:《thinkphp入门教程》、《thinkphp模板操作技巧总结》、《thinkphp常用方法总结》、《codeigniter入门教程》、《ci(codeigniter)框架进阶教程》、《zend framework框架入门教程》及《php模板技术总结》。
希望本文所述对大家基于thinkphp框架的php程序设计有所帮助。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!