Hook.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace crmeb\utils;
  12. use think\helper\Str;
  13. /**
  14. *
  15. * Class Hook
  16. * @package crmeb\utils
  17. */
  18. class Hook
  19. {
  20. /**
  21. * 类名
  22. * @var string
  23. */
  24. protected $namespace;
  25. /**
  26. * 方法前缀
  27. * @var string
  28. */
  29. protected $prefix;
  30. /**
  31. * 构造方法
  32. * Hook constructor.
  33. * @param string $namespace
  34. * @param string|null $prefix
  35. */
  36. public function __construct(string $namespace, string $prefix = null)
  37. {
  38. $this->namespace = $namespace;
  39. if ($prefix) {
  40. $this->prefix = $prefix;
  41. }
  42. }
  43. /**
  44. * 执行挂载方法
  45. * @param string $hookName
  46. * @param mixed ...$arguments
  47. * @return bool
  48. */
  49. public function listen(string $hookName, ...$arguments)
  50. {
  51. if (class_exists($this->namespace)) {
  52. $handle = app()->make($this->namespace);
  53. $hookName = Str::studly(($this->prefix ?: '') . ucfirst($hookName));
  54. if (method_exists($handle, $hookName)) {
  55. try {
  56. return call_user_func_array([$handle, $hookName], $arguments);
  57. } catch (\Throwable $e) {
  58. }
  59. }
  60. }
  61. return false;
  62. }
  63. }