Component.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /**
  3. * Link : http://www.phpcorner.net
  4. * User : qingbing<780042175@qq.com>
  5. * Date : 2018-12-05
  6. * Version : 1.0
  7. */
  8. namespace Abstracts;
  9. use Config;
  10. use Helper\Exception;
  11. abstract class Component extends Base
  12. {
  13. /* @var Component[] */
  14. private static $_instances = [];
  15. /**
  16. * 组件实例化
  17. * @param mixed $configs
  18. * @return $this
  19. * @throws Exception
  20. */
  21. public static function getInstance($configs = null)
  22. {
  23. if (null === $configs) {
  24. throw new Exception('组件实例化参数为空', 100300101);
  25. }
  26. if (is_string($configs)) {
  27. $configs = Config::getInstance($configs)->getAll();
  28. } else if (!is_array($configs)) {
  29. throw new Exception('组件实例化参数错误', 100300102);
  30. } else if (isset($configs['c-file'])) {
  31. if (isset($configs['c-group']) && !empty($configs['c-group'])) {
  32. $configs = Config::getInstance($configs['c-file'], $configs['c-group'])->getAll();
  33. } else {
  34. $configs = Config::getInstance($configs['c-file'])->getAll();
  35. }
  36. }
  37. $className = get_called_class();
  38. $id = md5($className . serialize($configs));
  39. if (!isset(self::$_instances[$id])) {
  40. if (!is_array($configs)) {
  41. throw new Exception('组件实例化时参数必须为数组', 100300103);
  42. }
  43. $instance = new $className($configs);
  44. if (!$instance instanceof Component) {
  45. throw new Exception('组件必须继承基类"\Abstracts\Component"', 100300104);
  46. }
  47. $instance->init();
  48. self::$_instances[$id] = $instance;
  49. }
  50. return self::$_instances[$id];
  51. }
  52. /**
  53. * 构造函数
  54. * constructor.
  55. * @param array $configs
  56. */
  57. final public function __construct(array $configs = [])
  58. {
  59. $this->configure($configs);
  60. }
  61. /**
  62. * 属性赋值后执行函数
  63. */
  64. abstract public function init();
  65. }