[[IT知识]] PHP反射机制深度解析:轻松获取类与方法注释

[复制链接]
查看: 25|回复: 0
发表于 7 天前 | 显示全部楼层 | 阅读模式
易博V9下载

PHP反射机制深度解析:轻松获取类与方法注释

通过php中的反射机制,获取该类的文档注释,再通过获取其所有的方法,获取方法的注释。

所用到的主要类及其方法如下:

  1. ReflectionClass
  2. ReflectionClass::getDocComment
  3. ReflectionClass::getMethods
  4. $method->getName()
  5. $method->getDocComment();
  6. $method->isProtected();
  7. $method->getParameters();
  8. $param->getName();
  9. $param->isDefaultValueAvailable();
  10. $param->getDefaultValue()
复制代码

测试类如下:

test.php

  1. <?php
  2. header("Content-type: text/html; charset=utf-8");
  3. require_once dir(__DIR__).'function.php';
  4. require_once dir(__DIR__).'TestClass.php';
  5. $class_name = 'TestClass';
  6. $reflection = new ReflectionClass ( $class_name );
  7. //通过反射获取类的注释
  8. $doc = $reflection->getDocComment ();
  9. //解析类的注释头
  10. $parase_result = DocParserFactory::getInstance()->parse ( $doc );
  11. $class_metadata = $parase_result;
  12. //输出测试
  13. var_dump ( $doc );
  14. echo "\r\n";
  15. print_r( $parase_result );
  16. echo "\r\n-----------------------------------\r\n";
  17. //获取类中的方法,设置获取public,protected类型方法
  18. $methods = $reflection->getMethods(ReflectionMethod::IS_PUBLIC + ReflectionMethod::IS_PROTECTED + ReflectionMethod::IS_PRIVATE);
  19. //遍历所有的方法
  20. foreach ($methods as $method) {
  21. //获取方法的注释
  22. $doc = $method->getDocComment();
  23. //解析注释
  24. $info = DocParserFactory::getInstance()->parse($doc);
  25. $metadata = $class_metadata + $info;
  26. //获取方法的类型
  27. $method_flag = $method->isProtected();//还可能是public,protected类型的
  28. //获取方法的参数
  29. $params = $method->getParameters();
  30. $position=0; //记录参数的次序
  31. foreach ($params as $param){
  32. $arguments[$param->getName()] = $position;
  33. //参数是否设置了默认参数,如果设置了,则获取其默认值
  34. $defaults[$position] = $param->isDefaultValueAvailable() ? $param->getDefaultValue() : NULL;
  35. $position++;
  36. }
  37. $call = array(
  38. 'class_name'=>$class_name,
  39. 'method_name'=>$method->getName(),
  40. 'arguments'=>$arguments,
  41. 'defaults'=>$defaults,
  42. 'metadata'=>$metadata,
  43. 'method_flag'=>$method_flag
  44. );
  45. print_r($call);
  46. echo "\r\n-----------------------------------\r\n";
  47. }
复制代码

function.php

  1. <?php
  2. require_once dir(__DIR__).'DocParser.php';
  3. /
  4. * 解析doc
  5. * 下面的DocParserFactory是对其的进一步封装,每次解析时,可以减少初始化DocParser的次数
  6. *
  7. * @param $php_doc_comment
  8. * @return array
  9. */
  10. function parse_doc($php_doc_comment) {
  11. $p = new DocParser ();
  12. return $p->parse ( $php_doc_comment );
  13. }
  14. /
  15. * Class DocParserFactory 解析doc
  16. *
  17. * @example
  18. * DocParserFactory::getInstance()->parse($doc);
  19. */
  20. class DocParserFactory{
  21. private static $p;
  22. private function DocParserFactory(){
  23. }
  24. public static function getInstance(){
  25. if(self::$p == null){
  26. self::$p = new DocParser ();
  27. }
  28. return self::$p;
  29. }
  30. }
复制代码

TestClass.php

  1. <?php
  2. /
  3. * A test class 在此处不能添加@ur,@param,@return 注释
  4. * 如果要将类的注释和方法的注释合并的话,添加了上面的注释,会将方法中的注释给覆盖掉
  5. */
  6. class TestClass {
  7. /
  8. * @desc 获取public方法
  9. *
  10. * @url GET pnrs
  11. * @param array $request_data
  12. * @return int id
  13. */
  14. public function getPublicMethod($no_default,$add_time = '0000-00-00') {
  15. echo "public";
  16. }
  17. /
  18. * @desc 获取private方法
  19. *
  20. * @url GET private_test
  21. * @return int id
  22. */
  23. private function getPrivateMethod($no_default,$time = '0000-00-00') {
  24. echo "private";
  25. }
  26. /
  27. * @desc 获取protected方法
  28. *
  29. * @url GET protected_test
  30. * @param $no_defalut,$time
  31. * @return int id
  32. */
  33. protected function getProtectedMethod($no_default,$time = '0000-00-00') {
  34. echo "protected";
  35. }
  36. }
复制代码

DocParser.php 该类源自一个开源项目

  1. <?php
  2. /
  3. * Parses the PHPDoc comments for metadata. Inspired by Documentor code base
  4. * @category Framework
  5. * @package restler
  6. * @subpackage helper
  7. * @author Murray Picton <info@murraypicton.com>
  8. * @author R.Arul Kumaran <arul@luracast.com>
  9. * @copyright 2010 Luracast
  10. * @license http://www.gnu.org/licenses/ GNU General Public License
  11. */
  12. class DocParser {
  13. private $params = array ();
  14. function parse($doc = '') {
  15. if ($doc == '') {
  16. return $this->params;
  17. }
  18. // Get the comment
  19. if (preg_match ( '#^/\*\*(.*)\*/#s', $doc, $comment ) === false)
  20. return $this->params;
  21. $comment = trim ( $comment [1] );
  22. // Get all the lines and strip the * from the first character
  23. if (preg_match_all ( '#^\s*\*(.*)#m', $comment, $lines ) === false)
  24. return $this->params;
  25. $this->parseLines ( $lines [1] );
  26. return $this->params;
  27. }
  28. private function parseLines($lines) {
  29. foreach ( $lines as $line ) {
  30. $parsedLine = $this->parseLine ( $line ); // Parse the line
  31. if ($parsedLine === false && ! isset ( $this->params ['description'] )) {
  32. if (isset ( $desc )) {
  33. // Store the first line in the short description
  34. $this->params ['description'] = implode ( PHP_EOL, $desc );
  35. }
  36. $desc = array ();
  37. } elseif ($parsedLine !== false) {
  38. $desc [] = $parsedLine; // Store the line in the long description
  39. }
  40. }
  41. $desc = implode ( ' ', $desc );
  42. if (! empty ( $desc ))
  43. $this->params ['long_description'] = $desc;
  44. }
  45. private function parseLine($line) {
  46. // trim the whitespace from the line
  47. $line = trim ( $line );
  48. if (empty ( $line ))
  49. return false; // Empty line
  50. if (strpos ( $line, '@' ) === 0) {
  51. if (strpos ( $line, ' ' ) > 0) {
  52. // Get the parameter name
  53. $param = substr ( $line, 1, strpos ( $line, ' ' ) - 1 );
  54. $value = substr ( $line, strlen ( $param ) + 2 ); // Get the value
  55. } else {
  56. $param = substr ( $line, 1 );
  57. $value = '';
  58. }
  59. // Parse the line and return false if the parameter is valid
  60. if ($this->setParam ( $param, $value ))
  61. return false;
  62. }
  63. return $line;
  64. }
  65. private function setParam($param, $value) {
  66. if ($param == 'param' || $param == 'return')
  67. $value = $this->formatParamOrReturn ( $value );
  68. if ($param == 'class')
  69. list ( $param, $value ) = $this->formatClass ( $value );
  70. if (empty ( $this->params [$param] )) {
  71. $this->params [$param] = $value;
  72. } else if ($param == 'param') {
  73. $arr = array (
  74. $this->params [$param],
  75. $value
  76. );
  77. $this->params [$param] = $arr;
  78. } else {
  79. $this->params [$param] = $value + $this->params [$param];
  80. }
  81. return true;
  82. }
  83. private function formatClass($value) {
  84. $r = preg_split ( "[\(|\)]", $value );
  85. if (is_array ( $r )) {
  86. $param = $r [0];
  87. parse_str ( $r [1], $value );
  88. foreach ( $value as $key => $val ) {
  89. $val = explode ( ',', $val );
  90. if (count ( $val ) > 1)
  91. $value [$key] = $val;
  92. }
  93. } else {
  94. $param = 'Unknown';
  95. }
  96. return array (
  97. $param,
  98. $value
  99. );
  100. }
  101. private function formatParamOrReturn($string) {
  102. $pos = strpos ( $string, ' ' );
  103. $type = substr ( $string, 0, $pos );
  104. return '(' . $type . ')' . substr ( $string, $pos + 1 );
  105. }
  106. }
复制代码
易博软件介绍
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

1、请认真发帖,禁止回复纯表情,纯数字等无意义的内容!帖子内容不要太简单!
2、提倡文明上网,净化网络环境!抵制低俗不良违法有害信息。
3、如果你对主帖作者的帖子不屑一顾的话,请勿回帖。谢谢合作!
3、问答求助区发帖求助后,如有其他用户热心帮您解决问题后,请自觉点击设为最佳答案按钮。

 
 
QQ在线客服
QQ技术支持
工作时间:
8:00-18:00
软著登字:
1361266号
官方微信扫一扫
weixin

QQ|小黑屋|Archiver|慈众营销 ( 粤ICP备15049986号 )|网站地图

自动发帖软件 | 自动发帖器 | 营销推广软件 | 网络营销工具 | 网络营销软件 | 网站推广工具 | 网络推广软件 | 网络推广工具 | 网页推广软件 | 信息发布软件 | 网站推广工具 | 网页推广软件

Powered by Discuz! X3.4   © 2012-2020 Comsenz Inc.  慈众科技 - Collect from 深圳吉宝泰佛文化有限公司 公司地址:罗湖区黄贝街道深南东路集浩大厦A1403

返回顶部 返回列表