Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^76) CHAPTER 7 ■ REFLECTION API


/**

This is soft metadata and its structure is not parsed by PHP
@see http://example.com/
*/
function mynameishardmetadata($myParamsToo) {}

The isUserDefined() method of ReflectionClass is an example of hard metadata being
used to execute different code paths. In Listing 7-1, it is used to ignore any classes that are not
user-defined.
The reflection API has a lot of is and has functions that can be used to create conditional
execution. It also has functions that can be used to invoke methods. When the two are put
together, you have the basis for a plug-in architecture.

Understanding the Reflection Plug-in Architecture.


The reflection-based plug-in architecture doesn’t really qualify as a pattern, as it’s not actually
a template; rather, it’s a series of concepts that combine to form a program’s architecture.
As you learned in earlier chapters, interfaces require any implementing class to declare all
of the methods that are defined in the interface. This is ideal for rigid systems, but can begin to
break down in larger, more complicated systems, where the two items interacting are them-
selves complex programs.
The reflection API plug-in approach is based on runtime-deterministic program capabilities;
that is, it allows you to create interfacing methods that are optional and are detected at first
use. These methods will be used only if they exist in the plug-in; otherwise, they will be ignored.
This can help you to avoid implementing complex interfaces, and it allows for more flexible
authoring.
For example, suppose you had the interface shown in Listing 7-2.

Listing 7-2. A Rigid Interface

interface IPlugin {
function getMenuItems();
function getArticles();
function getSideBars();
}
class SomePlugin implements IPlugin {
public function getMenuItems() {
//We don't have any menu items
return null;
}
public function getArticles() {
//We don't have any articles
return null;
}
public function getSideBars() {
//We have a sidebar
return array('SideBarItem');
}
}

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

Free download pdf