将PHP Doc注释解析为数据结构 [英] Parsing PHP Doc Comments into a Data Structure
问题描述
我正在PHP中使用Reflection API从方法中提取DocComment(PHPDoc)字符串
I'm using the Reflection API in PHP to pull a DocComment (PHPDoc) string from a method
$r = new ReflectionMethod($object);
$comment = $r->getDocComment();
这将返回一个看起来像这样的字符串(取决于方法的记录方式)
This will return a string that looks something like this (depending on how well the method was documented)
/**
* Does this great things
*
* @param string $thing
* @return Some_Great_Thing
*/
是否有任何内置方法或函数可以将PHP Doc注释字符串解析为数据结构?
Are there any built-in methods or functions that can parse a PHP Doc Comment String into a data structure?
$object = some_magic_function_or_method($comment_string);
echo 'Returns a: ', $object->return;
缺少这一点,我应该自己研究 PHPDoc源代码的哪一部分.
Lacking that, what part of the PHPDoc source code should I be looking at the do this myself.
缺少和/或除此之外,是否有第三方代码被认为比PHPDoc代码更好"?
Lacking and/or in addition to that, is there third party code that's considered "better" at this that the PHPDoc code?
我意识到解析这些字符串不是火箭科学,甚至不是计算机科学,但是我更喜欢一个经过良好测试的库/例程/方法,该库/例程/方法是为处理许多过时的,半不正确的PHP而构建的.野外可能存在的文档代码.
I realize parsing these strings isn't rocket science, or even computer science, but I'd prefer a well tested library/routine/method that's been built to deal with a lot of the janky, semi-non-correct PHP Doc code that might exist in the wild.
推荐答案
我对此还没有提到感到惊讶:使用Zend Framework的 Zend_Reflection 怎么办?这可能会派上用场,特别是如果您使用的是基于Zend Framework构建的软件(例如Magento).
I am surprised this wasn't mentioned yet: what about using Zend_Reflection of Zend Framework? This may come in handy especially if you work with a software built on Zend Framework like Magento.
有关某些代码示例和API文档以获取可用方法.
See the Zend Framework Manual for some code examples and the API Documentation for the available methods.
执行此操作的方法有多种:
There are different ways to do this:
- 将文件名传递给Zend_Reflection_File.
- 将对象传递给Zend_Reflection_Class.
- 将对象和方法名称传递给Zend_Reflection_Method.
- 如果真的只有注释字符串,甚至可以将一个小的虚拟类的代码放在一起,将其保存到一个临时文件中,然后将该文件传递给Zend_Reflection_File.
让我们开始一个简单的例子,并假设您有要检查的现有类.
Let's go for the simple case and assume you have an existing class you want to inspect.
代码将如下所示(未经测试,请原谅我):
The code would be like this (untested, please forgive me):
$method = new Zend_Reflection_Method($class, 'yourMethod');
$docblock = $method->getDocBlock();
if ($docBlock->hasTag('return')) {
$tagReturn = $docBlock->getTag('return'); // $tagReturn is an instance of Zend_Reflection_Docblock_Tag_Return
echo "Returns a: " . $tagReturn->getType() . "<br>";
echo "Comment for return type: " . $tagReturn->getDescription();
}
这篇关于将PHP Doc注释解析为数据结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!