Macroable.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006-2015 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: yunwuxin <448901948@qq.com>
  10. // +----------------------------------------------------------------------
  11. namespace think\helper;
  12. use Closure;
  13. use think\exception\FuncNotFoundException;
  14. trait Macroable
  15. {
  16. /**
  17. * 方法注入.
  18. *
  19. * @var Closure[]
  20. */
  21. protected static $macro = [];
  22. /**
  23. * 设置方法注入.
  24. *
  25. * @param string $method
  26. * @param Closure $closure
  27. *
  28. * @return void
  29. */
  30. public static function macro(string $method, Closure $closure)
  31. {
  32. static::$macro[$method] = $closure;
  33. }
  34. /**
  35. * 检查方法是否已经有注入
  36. *
  37. * @param string $name
  38. * @return bool
  39. */
  40. public static function hasMacro(string $method)
  41. {
  42. return isset(static::$macro[$method]);
  43. }
  44. public function __call($method, $args)
  45. {
  46. if (!isset(static::$macro[$method])) {
  47. throw new FuncNotFoundException('method not exists: ' . static::class . '::' . $method . '()', "{static::class}::{$method}");
  48. }
  49. return call_user_func_array(static::$macro[$method]->bindTo($this, static::class), $args);
  50. }
  51. public static function __callStatic($method, $args)
  52. {
  53. if (!isset(static::$macro[$method])) {
  54. throw new FuncNotFoundException('method not exists: ' . static::class . '::' . $method . '()', "{static::class}::{$method}");
  55. }
  56. return call_user_func_array(static::$macro[$method]->bindTo(null, static::class), $args);
  57. }
  58. }