Service.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace common\components;
  3. use Yii;
  4. use yii\base\Component;
  5. use yii\base\InvalidConfigException;
  6. use common\traits\BaseAction;
  7. /**
  8. * 自定义服务组件
  9. * @Author bing
  10. * @DateTime 2021-08-11 16:43:49
  11. * @copyright: Copyright (c) 2020 广东七件事集团
  12. */
  13. class Service extends Component
  14. {
  15. // 子服务
  16. public $childService;
  17. // 已实例化的子服务
  18. protected $_childService;
  19. /**
  20. * 获取 services 里面配置的子服务 childService 的实例
  21. * @Author bing
  22. * @DateTime 2021-08-11 16:44:58
  23. * @copyright: Copyright (c) 2020 广东七件事集团
  24. * @param [type] $childServiceName
  25. * @throws InvalidConfigException
  26. * @return mixed
  27. */
  28. protected function getChildService($childServiceName)
  29. {
  30. if (!isset($this->_childService[$childServiceName])) {
  31. $childService = $this->childService;
  32. if (isset($childService[$childServiceName])) {
  33. $service = $childService[$childServiceName];
  34. $this->_childService[$childServiceName] = Yii::createObject($service);
  35. } else {
  36. throw new InvalidConfigException('未找到 [' . $childServiceName . '] 此子模块 ' . get_called_class() . ', 需要先进行配置! ');
  37. }
  38. }
  39. return $this->_childService[$childServiceName] ?? null;
  40. }
  41. /**
  42. * 魔术方法获取子服务
  43. * @Author bing
  44. * @DateTime 2021-08-11 16:45:57
  45. * @copyright: Copyright (c) 2020 广东七件事集团
  46. * @param [type] $attr
  47. * @return mixed
  48. * @throws InvalidConfigException
  49. */
  50. public function __get($attr)
  51. {
  52. return $this->getChildService($attr);
  53. }
  54. }