Home PHP Framework ThinkPHP Analyze thinkPHP's method of implementing hooks based on reflection

Analyze thinkPHP's method of implementing hooks based on reflection

May 26, 2021 pm 04:23 PM
thinkphp reflection hook

下面由thinkphp框架教程栏目给大家解析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 &#39;detail&#39; . "\r\n";
  }
  public function test($year = 2014, $month = 4, $day = 21) {
    echo $year . &#39;--&#39; . $month . &#39;--&#39; . $day . "\r\n";
  }
  public function _before_detail() {
    echo __FUNCTION__ . "\r\n";
  }
  public function _after_detail() {
    echo __FUNCTION__ . "\r\n";
  }
}
// 执行detail方法
$method = new ReflectionMethod(&#39;BlogAction&#39;, &#39;detail&#39;);
$instance = new BlogAction();
// 进行权限判断
if ($method->isPublic()) {
  $class = new ReflectionClass(&#39;BlogAction&#39;);
  // 执行前置方法
  if ($class->hasMethod(&#39;_before_detail&#39;)) {
    $beforeMethod = $class->getMethod(&#39;_before_detail&#39;);
    if ($beforeMethod->isPublic()) {
      $beforeMethod->invoke($instance);
    }
  }
  $method->invoke(new BlogAction);
  // 执行后置方法
  if ($class->hasMethod(&#39;_after_detail&#39;)) {
    $beforeMethod = $class->getMethod(&#39;_after_detail&#39;);
    if ($beforeMethod->isPublic()) {
      $beforeMethod->invoke($instance);
    }
  }
}
// 执行带参数的方法
$method = new ReflectionMethod(&#39;BlogAction&#39;, &#39;test&#39;);
$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 &#39;parameters is wrong!&#39;;
}
Copy after login

另一段代码参考

/**
 * 执行App控制器
 */
public function execApp() {
  // 创建action控制器实例
  $className = MODULE_NAME . &#39;Controller&#39;;
  $namespaceClassName = &#39;\\apps\\&#39; . APP_NAME . &#39;\\controller\\&#39; . $className;
  load_class($namespaceClassName, false);
  if (!class_exists($namespaceClassName)) {
    throw new \Exception(&#39;Oops! Module not found : &#39; . $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, &#39;__call&#39;);
    $methodInfo->invokeArgs($controller, array($action, &#39;&#39;));
  }
  return;
}
Copy after login

相关推荐:最新的10个thinkphp视频教程

The above is the detailed content of Analyze thinkPHP's method of implementing hooks based on reflection. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1263
29
C# Tutorial
1237
24
How to run thinkphp project How to run thinkphp project Apr 09, 2024 pm 05:33 PM

To run the ThinkPHP project, you need to: install Composer; use Composer to create the project; enter the project directory and execute php bin/console serve; visit http://localhost:8000 to view the welcome page.

There are several versions of thinkphp There are several versions of thinkphp Apr 09, 2024 pm 06:09 PM

ThinkPHP has multiple versions designed for different PHP versions. Major versions include 3.2, 5.0, 5.1, and 6.0, while minor versions are used to fix bugs and provide new features. The latest stable version is ThinkPHP 6.0.16. When choosing a version, consider the PHP version, feature requirements, and community support. It is recommended to use the latest stable version for best performance and support.

Reflection mechanism implementation of interfaces and abstract classes in Java Reflection mechanism implementation of interfaces and abstract classes in Java May 02, 2024 pm 05:18 PM

The reflection mechanism allows programs to obtain and modify class information at runtime. It can be used to implement reflection of interfaces and abstract classes: Interface reflection: obtain the interface reflection object through Class.forName() and access its metadata (name, method and field) . Reflection of abstract classes: Similar to interfaces, you can obtain the reflection object of an abstract class and access its metadata and non-abstract methods. Practical case: The reflection mechanism can be used to implement dynamic proxies, intercepting calls to interface methods at runtime by dynamically creating proxy classes.

How to use reflection to access private fields and methods in golang How to use reflection to access private fields and methods in golang May 03, 2024 pm 12:15 PM

You can use reflection to access private fields and methods in Go language: To access private fields: obtain the reflection value of the value through reflect.ValueOf(), then use FieldByName() to obtain the reflection value of the field, and call the String() method to print the value of the field . Call a private method: also obtain the reflection value of the value through reflect.ValueOf(), then use MethodByName() to obtain the reflection value of the method, and finally call the Call() method to execute the method. Practical case: Modify private field values ​​and call private methods through reflection to achieve object control and unit test coverage.

How to run thinkphp How to run thinkphp Apr 09, 2024 pm 05:39 PM

Steps to run ThinkPHP Framework locally: Download and unzip ThinkPHP Framework to a local directory. Create a virtual host (optional) pointing to the ThinkPHP root directory. Configure database connection parameters. Start the web server. Initialize the ThinkPHP application. Access the ThinkPHP application URL and run it.

Which one is better, laravel or thinkphp? Which one is better, laravel or thinkphp? Apr 09, 2024 pm 03:18 PM

Performance comparison of Laravel and ThinkPHP frameworks: ThinkPHP generally performs better than Laravel, focusing on optimization and caching. Laravel performs well, but for complex applications, ThinkPHP may be a better fit.

How to install thinkphp How to install thinkphp Apr 09, 2024 pm 05:42 PM

ThinkPHP installation steps: Prepare PHP, Composer, and MySQL environments. Create projects using Composer. Install the ThinkPHP framework and dependencies. Configure database connection. Generate application code. Launch the application and visit http://localhost:8000.

How is the performance of thinkphp? How is the performance of thinkphp? Apr 09, 2024 pm 05:24 PM

ThinkPHP is a high-performance PHP framework with advantages such as caching mechanism, code optimization, parallel processing and database optimization. Official performance tests show that it can handle more than 10,000 requests per second and is widely used in large-scale websites and enterprise systems such as JD.com and Ctrip in actual applications.

See all articles