Helper.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. namespace Qii\Autoloader;
  3. /**
  4. * Helper 将自动注册到系统 Helper中,直接调用即可
  5. *
  6. * @author Jinhui Zhu<jinhui.zhu@live.cn>2015-10-24 23:18
  7. * @version 1.2
  8. */
  9. class Helper
  10. {
  11. const VERSION = '1.2';
  12. /**
  13. * @var $helpers helper类
  14. */
  15. public static $helpers = array();
  16. public function __construct()
  17. {
  18. self::$helpers = array();
  19. }
  20. /**
  21. * 使用属性返回helper类
  22. * @param string $name 不带helper\的类名
  23. * @return object
  24. */
  25. public function __get($name)
  26. {
  27. if (substr($name, 0, 7) == 'helper\\') return $this->get($name);
  28. return $this->get('helper\\' . $name);
  29. }
  30. /**
  31. * 获取helper类,如果没有实例化就抛出异常
  32. * @param string $helper
  33. * @return object
  34. */
  35. public function get($helper)
  36. {
  37. if (isset(self::$helpers[$helper])) return self::$helpers[$helper];
  38. throw new \Qii\Exceptions\CallUndefinedClass(\Qii::i('1105', $helper), __LINE__);
  39. }
  40. /*
  41. * 自动加载Helper目录中文件,支持自动实例化对象
  42. * @param string $appPath 自动加载指定目录中文件
  43. */
  44. public function load($appPath = '')
  45. {
  46. if ($appPath == '') {
  47. return;
  48. }
  49. if (!is_dir($appPath . DS . 'helper')) {
  50. return;
  51. }
  52. foreach (glob(str_replace("//", DS, $appPath . DS . 'helper' . DS . '*.php'), GLOB_BRACE) AS $file) {
  53. if(\Qii\Autoloader\Import::requires($file)){
  54. //如果里边包含class的话就将class注册到Qii::instance('class');
  55. $className = 'helper\\'. pathinfo($file)['filename'];
  56. if (!isset(self::$helpers[$className]) && class_exists($className, false)) {
  57. self::$helpers[$className] = \Qii\Autoloader\Psr4::getInstance()->instance($className);
  58. }
  59. }
  60. }
  61. }
  62. }