BaseService.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. declare(strict_types=1);
  3. namespace app\common\service;
  4. abstract class BaseService{
  5. protected static $service=[];
  6. protected static $obj=[];
  7. protected $safekey;
  8. /**
  9. * @param array $arr 参数
  10. * @param string $key 为创建线程安全对象的唯一识别key
  11. * @return mixed|static
  12. */
  13. public static function newInstance(array $arr=[],mixed $safekey=null)
  14. {
  15. $classname=$safekey??get_called_class();
  16. if(!isset(self::$service[$classname])){
  17. $service = new static();
  18. $service->safekey=$safekey;
  19. if(count($arr)>0){
  20. $service->setParam($arr);
  21. }
  22. self::$service[$classname]=$service;
  23. self::$obj[$classname]=[];
  24. try{
  25. $service->init();
  26. }catch (\Exception $e){
  27. $service->destroy();
  28. throw $e;
  29. }
  30. }
  31. return self::$service[$classname];
  32. }
  33. public function destroy()
  34. {
  35. $classname=$this->safekey??get_called_class();
  36. unset(self::$service[$classname]);
  37. unset(self::$obj[$classname]);
  38. }
  39. public function setParam(array $arr)
  40. {
  41. $class = new \ReflectionClass($this);
  42. $property=$class->getProperties();
  43. foreach($property as $value) {
  44. $key=$value->name;
  45. foreach ($arr as $pk=>$pv) {
  46. if ($pk == $key) {
  47. $attribute=$class->getProperty($key);
  48. $attribute->setAccessible(true);
  49. $attribute->setValue($this,$pv);
  50. }
  51. }
  52. }
  53. return $this;
  54. }
  55. protected function setObj(string $classname,object $objval)
  56. {
  57. $class=$this->safekey??get_called_class();
  58. self::$obj[$class][$classname]=$objval;
  59. }
  60. protected function getObj(string $classname,bool $allowNull=false,string $message='')
  61. {
  62. $class=$this->safekey??get_called_class();
  63. if(!isset(self::$obj[$class][$classname])){
  64. if($allowNull){
  65. return null;
  66. }
  67. if($message){
  68. throw new \Exception($message);
  69. }else{
  70. throw new \Exception('系统异常,缺少对象'.$classname);
  71. }
  72. }
  73. return self::$obj[$class][$classname];
  74. }
  75. abstract protected function init();
  76. }