PHP利用反射实现插件功能

Standard

以下代码搜于google,出处不详.转贴于此纯为记录

<?php
//---iplugin.php------------------------------------
 interface Iplugin{
  public static function getName();
 }
//---plug1.php--------------------------------------
 class Plug1 implements Iplugin {
  public static function getName(){
    return 'Plug1';
  }    
  public static function getMenuItems(){
    return array(array('description'=>'Plug1','link'=>'/plug1'));
  }    
  public static function getArticles(){
    return array(array('path'=>'/plug1/aid=1','title'=>'Title of Plug1','text'=>'Content of Plug1'));    
  }
 }
//---plug2.php--------------------------------------
 class Plug2 implements Iplugin {
  public static function getName(){
    return 'Plug2';
  }    
  public static function getMenuItems(){
    return array(array('description'=>'plug2','link'=>'/plug1'));
  }    
  public static function getArticles(){
    return array(array('path'=>'/plug2/aid=1','title'=>'Title of Plug2','text'=>'Content of Plug2'));    
  }
 }
//---reflection.php---------------------------------
 function findPlugins(){
  $plugins = array();
  foreach (get_declared_classes() as $class){
    $reflectionClass = new ReflectionClass($class);
    if ($reflectionClass->implementsInterface('Iplugin')) {
     $plugins[] = $reflectionClass;
    }
  }    
  return $plugins;    
 }
 function computeMenu(){    
  $menu = array();    
  foreach (findPlugins() as $plugin){    
    if ($plugin->hasMethod('getMenuItems')) {    
     $reflectionMethod = $plugin->getMethod('getMenuItems');    
     if ($reflectionMethod->isStatic()) {    
      $items = $reflectionMethod->invoke(null);    
     } else {    
      $pluginInstance = $plugin->newInstance();    
      $items = $reflectionMethod->invoke($pluginInstance);    
     }    
     $menu = array_merge($menu,$items);    
    }    
  }
  return $menu;    
 }
 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;    
 }
//---index.php--------------------------------------
 $menu = computeMenu();    
 $articles = computeArticles();
 print_r($menu);
 print_r($articles);
?>

2 thoughts on “PHP利用反射实现插件功能

  1. 明月千里难以触摸,对你的思念无处寄托,举杯邀明月,说:福多!钱多!快乐多!中秋快乐!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.