Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^86) CHAPTER 7 ■ REFLECTION API
When run, this parser outputs the following:
Array
(
[0] => This is a doccomment comment
[1] => This doccomment documents the class demo
)
Array
(
[author] => Kevin McArthur
[example] => Array
(
[0] => This is a multiline example and this is more than valid
[1] => This is another separate example.
)
)
In this parsing process, you need to iterate the tokens produced by the tokenization func-
tion. During this iteration, you make a couple of assumptions. If a tag has not occurred yet, you
assume that all text is a comment. Once a tag is found, all text is then associated with that tag
until a new tag is found.
Note that text elements can occur more than once per tag and must be appended to the
tag. Because tags can occur multiple times, you cannot just append the text. Instead, you need
to assign a tag a unique ID to differentiate it from other tags that happen to have the same
name. Later, you combine both the tags and their unique IDs, producing arrays when there are
multiple tags.
You could stop here and format the output. But then, you have not really associated the
rest of the program metadata with the comments or created a package that is easy to use. Those
goals require extending the reflection API to add the parsed doccomments to the reflection
classes, as explained next.


Extending the Reflection API


Reflection API classes are like all OOP classes—they can be derived from and extended. In this
section, you will learn how to overload the reflection API to support advanced documentation
parsing as part of the reflection API itself. Once you have successfully extended the reflection
API, you will be able to create an extremely powerful metadata system.

Integrating the Parser with the Reflection API.


To start, let’s integrate the docblock parser from the previous listing with the reflection API.
You do this by extending the core Reflection class and adding the parser as a static method.
Listing 7-12 shows this extension. Place this and all subsequent reflection classes in a common
include file called DocumentingReflection.php.

McArthur_819-9C07.fm Page 86 Friday, February 22, 2008 8:59 AM

Free download pdf