Hook.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace crmeb\utils;
  3. use think\helper\Str;
  4. /**
  5. *
  6. * Class Hook
  7. * @package crmeb\utils
  8. */
  9. class Hook
  10. {
  11. /**
  12. * 类名
  13. * @var string
  14. */
  15. protected $namespace;
  16. /**
  17. * 方法前缀
  18. * @var string
  19. */
  20. protected $prefix;
  21. /**
  22. * 构造方法
  23. * Hook constructor.
  24. * @param string $namespace
  25. * @param string|null $prefix
  26. */
  27. public function __construct(string $namespace, string $prefix = null)
  28. {
  29. $this->namespace = $namespace;
  30. if ($prefix) {
  31. $this->prefix = $prefix;
  32. }
  33. }
  34. /**
  35. * 执行挂载方法
  36. * @param string $hookName
  37. * @param mixed ...$arguments
  38. * @return bool
  39. */
  40. public function listen(string $hookName, ...$arguments)
  41. {
  42. if (class_exists($this->namespace)) {
  43. $handle = new $this->namespace;
  44. $hookName = Str::studly(($this->prefix ?: '') . ucfirst($hookName));
  45. if (method_exists($handle, $hookName)) {
  46. try {
  47. return $handle->{$hookName}(...$arguments);
  48. } catch (\Throwable $e) {
  49. }
  50. }
  51. }
  52. return false;
  53. }
  54. }