Pro PHP- Patterns, Frameworks, Testing and More

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

Now that you have a ReflectionMethod instance, you need to determine if your API method
should be called statically. If the method is static, you can just call invoke() without creating an
instance of the plug-in. The invoke() method of ReflectionMethod has the following signature:

public mixed invoke(stdclass object, mixed args=null)

To invoke a static method, you must pass an implicit null as the first parameter to the
invoke() method.
If, on the other hand, the method is non-static, you need to get an instance of the plug-in on
which to invoke the method. To get an instance of a class from a ReflectionClass object, you call
the newInstance() method. Then, assuming all went well constructing the instance, you can
call the invoke() method of ReflectionMethod, passing it the instance returned by newInstance().
Whatever menu items were returned by each plug-in should then be merged into the $menu
array. When all your plug-ins have completed processing, the entire $menu array is returned.
Using this same technique, you can continue to create facilities for articles and sidebars,
as shown in Listing 7-6.

Listing 7-6. Determining Class Members for Articles and Sidebars

function computeArticles() {
$articles = array();
foreach(findPlugins() as $plugin) {
if($plugin->hasMethod('getArticles')) {
$reflectionMethod = $plugin->getMethod('getArticles');
if($reflectionMethod->isStatic()) {
$items = $reflectionMethod->invoke(null);
} else {
$pluginInstance = $plugin->newInstance();
$items = $reflectionMethod->invoke($pluginInstance);
}
$articles = array_merge($articles, $items);
}
}
return $articles;
}

function computeSidebars() {
$sidebars = array();
foreach(findPlugins() as $plugin) {
if($plugin->hasMethod('getSidebars')) {
$reflectionMethod = $plugin->getMethod('getSidebars');
if($reflectionMethod->isStatic()) {
$items = $reflectionMethod->invoke(null);
} else {
$pluginInstance = $plugin->newInstance();
$items = $reflectionMethod->invoke($pluginInstance);
}

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

Free download pdf