当前位置:Gxlcms > PHP教程 > php如何利用反射实现插件代码示例

php如何利用反射实现插件代码示例

时间:2021-07-01 10:21:17 帮助过:3人阅读

这篇文章主要介绍了php利用反射实现插件机制的方法,涉及php反射机制与插件的实现技巧,需要的朋友可以参考下

本文实例讲述了php利用反射实现插件机制的方法。分享给大家供大家参考。具体实现方法如下:

代码如下:

  1. <?php
  2. /**
  3. * @name PHP反射API--利用反射技术实现的插件系统架构
  4. */
  5. interface Iplugin{
  6. public static function getName();
  7. }
  8. function findPlugins(){
  9. $plugins = array();
  10. foreach (get_declared_classes() as $class){
  11. $reflectionClass = new ReflectionClass($class);
  12. if ($reflectionClass->implementsInterface('Iplugin')) {
  13. $plugins[] = $reflectionClass;
  14. }
  15. }
  16. return $plugins;
  17. }
  18. function computeMenu(){
  19. $menu = array();
  20. foreach (findPlugins() as $plugin){
  21. if ($plugin->hasMethod('getMenuItems')) {
  22. $reflectionMethod = $plugin->getMethod('getMenuItems');
  23. if ($reflectionMethod->isStatic()) {
  24. $items = $reflectionMethod->invoke(null);
  25. } else {
  26. $pluginInstance = $plugin->newInstance();
  27. $items = $reflectionMethod->invoke($pluginInstance);
  28. }
  29. $menu = array_merge($menu,$items);
  30. }
  31. }
  32. return $menu;
  33. }
  34. function computeArticles(){
  35. $articles = array();
  36. foreach (findPlugins() as $plugin){
  37. if ($plugin->hasMethod('getArticles')) {
  38. $reflectionMethod = $plugin->getMethod('getArticles');
  39. if ($reflectionMethod->isStatic()) {
  40. $items = $reflectionMethod->invoke(null);
  41. } else {
  42. $pluginInstance = $plugin->newInstance();
  43. $items = $reflectionMethod->invoke($pluginInstance);
  44. }
  45. $articles = array_merge($articles,$items);
  46. }
  47. }
  48. return $articles;
  49. }
  50. class MycoolPugin implements Iplugin {
  51. public static function getName(){
  52. return 'MycoolPlugin';
  53. }
  54. public static function getMenuItems(){
  55. return array(array('description'=>'MycoolPlugin','link'=>'/MyCoolPlugin'));
  56. }
  57. public static function getArticles(){
  58. return array(array('path'=>'/MycoolPlugin','title'=>'This is a really cool article','text'=> 'xxxxxxxxx' ));
  59. }
  60. }
  61. $menu = computeMenu();
  62. $articles = computeArticles();
  63. print_r($menu);
  64. print_r($articles);

以上就是php如何利用反射实现插件代码示例的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行