Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 7 ■ REFLECTION API^99

This code has the following output:

demoMethod
Array
(
[0] => This is the first test method
)
param1 mixed The first comment <a href="http://www.apress.com">See the
website</a>
param2 string The second comment.

demoMethod2
Array
(
[0] => This is the second test method
)
param1 mixed The first comment of the second method
param2 string The second comment of the second method

Adding Attributes


Attributes are programming language elements that are used to add programmatically acces-
sible metadata to your application, most commonly to communicate with another program
that may be working in conjunction with your code. Although attributes can be very complex,
the simplest attributes declare that some action can be done with a class.
PHP does not natively support attributes. However, in the same way that you added reflec-
tion abilities to parse documentation, you can add attributes.
The easiest way to add an attribute to a class is to just define another PHPDoc tag, such as
@attribute, and then extend your Reflection* classes to expose this tag as a collection. If this
extension is done correctly, you could then write classes that look at attributes of the classes
and methods and make a programmatic decision.
As an example, I’ll demonstrate how to add an attribute for a web services application
to mark a class or some methods as safe to expose via a web service. To start, add a method to
get attributes (tags named attribute) in the DocumentingReflectionMethod class, as shown in
Listing 7-22.

Listing 7-22. Adding the getAttributes Method to DocumentingReflectionMethod
(DocumentingReflection.php)

public function getAttributes() {

if(array_key_exists('attribute', $this->_tags)) {

$rawAttributes = $this->_tags['attribute'];
$attributes = array();

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

Free download pdf