1 | <?php |
||
10 | abstract class ContainerBuilder |
||
11 | { |
||
12 | /** |
||
13 | * ContainerBuilder constructor. |
||
14 | * @param array $annotations 需加载的注释和顺序 |
||
15 | * @param Cache $cache |
||
16 | * 语法 http://jmespath.org/tutorial.html |
||
17 | * |
||
18 | * [ |
||
19 | * [PropertyAnnotationHandler::class, 'property'], |
||
20 | * ... |
||
21 | * ]; |
||
22 | * |
||
23 | */ |
||
24 | 89 | public function __construct(array $annotations, Cache $cache) |
|
25 | { |
||
26 | 89 | $this->annotations = $annotations; |
|
27 | 89 | $this->cache = $cache; |
|
28 | 89 | } |
|
29 | |||
30 | 1 | public function setCache(Cache $cache) |
|
31 | 1 | { |
|
32 | $this->cache = $cache; |
||
33 | } |
||
34 | /** |
||
35 | * load from class with local cache |
||
36 | * @param string $className |
||
37 | * @return object |
||
38 | */ |
||
39 | 89 | public function build($className) |
|
40 | 1 | { |
|
41 | //TODO【重要】 使用全局的缓存版本号, 而不是针对每个文件判断缓存过期与否 |
||
42 | 89 | $rfl = new \ReflectionClass($className) or \PhpBoot\abort("load class $className failed"); |
|
43 | 89 | $fileName = $rfl->getFileName(); |
|
44 | 89 | $key = str_replace('\\','.',get_class($this)).md5(serialize($this->annotations).$fileName.$className); |
|
45 | 89 | $cache = new CheckableCache($this->cache); |
|
46 | 89 | $res = $cache->get($key, $this); |
|
47 | 89 | if($res === $this){ |
|
48 | try{ |
||
49 | 21 | $meta = $this->buildWithoutCache($className); |
|
50 | 21 | $cache->set($key, $meta, 0, $fileName?new ClassModifiedChecker($className):null); |
|
51 | 21 | return $meta; |
|
52 | }catch (\Exception $e){ |
||
53 | Logger::warning(__METHOD__.' failed with '.$e->getMessage()); |
||
54 | $cache->set($key, $e->getMessage(), 0, $fileName?new ClassModifiedChecker($className):null); |
||
55 | throw $e; |
||
56 | } |
||
57 | 74 | }elseif(is_string($res)){ |
|
58 | \PhpBoot\abort($res); |
||
59 | }else{ |
||
60 | 74 | return $res; |
|
61 | } |
||
62 | } |
||
63 | |||
64 | /** |
||
65 | * @param string $className |
||
66 | * @return object |
||
67 | */ |
||
68 | abstract protected function createContainer($className); |
||
69 | |||
70 | 21 | protected function postCreateContainer($object) |
|
71 | { |
||
72 | |||
78 | /** |
||
79 | * @param $className |
||
80 | * @return object |
||
81 | */ |
||
82 | 21 | public function buildWithoutCache($className) |
|
101 | |||
102 | /** |
||
103 | * @var array |
||
104 | */ |
||
105 | private $annotations=[]; |
||
106 | /** |
||
107 | * @var Cache |
||
108 | */ |
||
109 | private $cache; |
||
110 | } |