ServiceContainer.php
2.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
<?php
namespace PgServiceSdk\Kernel;
use Pimple\Container;
use PgServiceSdk\Kernel\Providers\ConfigProvider;
use PgServiceSdk\Kernel\Providers\RequestProvider;
use PgServiceSdk\Kernel\Providers\HttpClientProvider;
/**
* Class ServiceContainer
* @package PgServiceSdk\Kernel
*
* @property \PgServiceSdk\Kernel\Config $config
* @property \GuzzleHttp\Client $http_client
* @property \Symfony\Component\HttpFoundation\Request $request
*/
class ServiceContainer extends Container
{
/**
* 服务提供者容器
*
* @var array
*/
protected $providers = [];
/**
* 用户自定义配置
*
* @var array
*/
protected $userConfig = [];
/**
* 默认的配置,子类可覆盖
*
* @var array
*/
protected $defaultConfig = [];
/**
* @var null|string
*/
protected $requestId = null;
/**
* ServiceContainer constructor.
* @param array $config
* @param array $values
* @param string $id
*/
public function __construct(array $config = [], array $values = array(), $id = null)
{
$this->registerProviders($this->getProviders());
parent::__construct($values);
$this->userConfig = $config;
$this->requestId = $id;
}
/**
* 获取请求 requestId
*
* @return string
*/
public function getRequestId()
{
return $this->requestId = ($this->requestId ?: md5(json_encode($this->userConfig)));
}
/**
* 获取配置
*
* @return array
*/
public function getConfig()
{
$base = [
// http://docs.guzzlephp.org/en/stable/request-options.html
'http' => [
'timeout' => 10.0,
'headers' => ['Accept' => 'application/json']
],
];
return array_replace_recursive($base, $this->defaultConfig, $this->userConfig['default']);
}
/**
* 获取服务提供者
*
* @return array
*/
public function getProviders()
{
return array_merge([
ConfigProvider::class,
HttpClientProvider::class,
RequestProvider::class
], $this->providers);
}
/**
* 注册服务提供者
*
* @param array $providers
*/
public function registerProviders(array $providers)
{
foreach ($providers as $provider) {
parent::register(new $provider());
}
}
/**
* @param string $name
*
* @return mixed
*/
public function __get($name)
{
return $this->offsetGet($name);
}
/**
* @param string $name
* @param mixed $value
*/
public function __set($name, $value)
{
$this->offsetSet($name, $value);
}
}