人人人妻人人人妻人人人,99精品国产综合久久久久五月天 ,欧美白人最猛性XXXXX,日韩AV无码免费播放

News新聞

業(yè)界新聞動態(tài)、技術(shù)前沿
Who are we?

您的位置:首頁      樂道系統(tǒng)FAQ      thinkPHP基于反射實現(xiàn)鉤子的方法分析

thinkPHP基于反射實現(xiàn)鉤子的方法分析

標(biāo)簽: 發(fā)布日期:2017-11-23 00:00:00 353

本文實例講述了thinkPHP基于反射實現(xiàn)鉤子的方法。分享給大家供大家參考,具體如下:

ThinkPHP框架的控制器模塊是如何實現(xiàn) 前控制器、后控制器,及如何執(zhí)行帶參數(shù)的方法?

PHP系統(tǒng)自帶的 ReflectionClass、ReflectionMethod 類,可以反射用戶自定義類的中屬性,方法的權(quán)限和參數(shù)等信息,通過這些信息可以準(zhǔn)確的控制方法的執(zhí)行。

ReflectionClass:

主要用的方法:

hasMethod(string)  是否存在某個方法
getMethod(string)  獲取方法

ReflectionMethod:

主要方法:

isPublic()    是否為 public 方法
getNumberOfParameters()  獲取參數(shù)個數(shù)
getParamters()  獲取參數(shù)信息
invoke( object $object [, mixed $parameter [, mixed $... ]] ) 執(zhí)行方法
invokeArgs(object obj, array args)  帶參數(shù)執(zhí)行方法

實例演示

<?php
class BlogAction {
  public function detail() {
    echo 'detail' . "\r\n";
  }
  public function test($year = 2014, $month = 4, $day = 21) {
    echo $year . '--' . $month . '--' . $day . "\r\n";
  }
  public function _before_detail() {
    echo __FUNCTION__ . "\r\n";
  }
  public function _after_detail() {
    echo __FUNCTION__ . "\r\n";
  }
}
// 執(zhí)行detail方法
$method = new ReflectionMethod('BlogAction', 'detail');
$instance = new BlogAction();
// 進(jìn)行權(quán)限判斷
if ($method->isPublic()) {
  $class = new ReflectionClass('BlogAction');
  // 執(zhí)行前置方法
  if ($class->hasMethod('_before_detail')) {
    $beforeMethod = $class->getMethod('_before_detail');
    if ($beforeMethod->isPublic()) {
      $beforeMethod->invoke($instance);
    }
  }
  $method->invoke(new BlogAction);
  // 執(zhí)行后置方法
  if ($class->hasMethod('_after_detail')) {
    $beforeMethod = $class->getMethod('_after_detail');
    if ($beforeMethod->isPublic()) {
      $beforeMethod->invoke($instance);
    }
  }
}
// 執(zhí)行帶參數(shù)的方法
$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!';
}