PhpRiot
Download This Article
Download this article in PDF format with all listings and files.

Price: $5.00 AUD
(Approx. $4.10 USD)

More information
Browse Articles
Ajax (4), APC (1), CAPTCHA (1), CSS (3), Debugging (1), File Upload (1), Google (3), Google Maps (2), JavaScript (12), JSON (2), MVC (1), MySQL (7), onbeforeunload (1), OOP (1), PHP (28), PhpDoc (1), PostgreSQL (6), Prototype (11), Reflection (1), RFC 1867 (1), Robots (1), Scriptaculous (1), SEO (1), Sessions (1), SimpleXML (1), Smarty (5), SOAP (1), SPL (1), Templates (2), W3C (1), XHTML (1), Zend Framework (1), Zend_Search_Lucene (1)

PhpRiot Newsletter
Your Email Address:

Advanced Documentation With Reflection In PHP 5

Extracting Code Comments With The Reflection API

Now you know how metadata is stored, and how to format it. To access metadata, we need to use the Reflection API.

The Reflection API is a series of classes new to PHP 5 which you provide the name of the item you wish to introspect. The class then has a number of methods and properties containing the relevant information.

You can reflect functions with ReflectionFunction, classes and interfaces with ReflectionClass.

To reflect a class you simply provide the name as a string to the constructor of ReflectionClass. We then have a number of properties and methods available, but the one you care about is the getDocComment() method.

Listing 9 listing-9.php
<?php
    $oClassReflect = new ReflectionClass("classname");
    $sDocComment = $oClassReflect->getDocComment();
?>

You now have the doc comment as a string, but it isn’t very useful. To parse the phpdoc style commenting from the comment use a series of string processing functions. Use a few regular expressions to remove the *‘s and then, normalize the values into an array of lines. Additionally, each line may have multiple successive tabs and these should be treated as a single tab.

Listing 10 listing-10.php
<?php
    $sDocComment = preg_replace("/(^[\\s]*\\/\\*\\*)
                                 |(^[\\s]\\*\\/)
                                 |(^[\\s]*\\*?\\s)
                                 |(^[\\s]*)
                                 |(^[\\t]*)/ixm", "", $sDocComment);
 
    $sDocComment = str_replace("\r", "", $sDocComment);
    $sDocComment = preg_replace("/([\\t])+/", "\t", $sDocComment);
    $aDocCommentLines = explode("\n", $sDocComment);
?>

Next you will want to loop through the resulting array and do some basic parsing. String processing is beyond the scope of this article so I will simply point you to our website and you can look at the working parser in the StormAPI package (/model/docgen/).

In This Article


Tagged in , ,