MediaWiki master
SpecBasedFactoryTrait.php
Go to the documentation of this file.
1<?php
8
9use Psr\Log\LoggerInterface;
10use Psr\Log\NullLogger;
11use UnexpectedValueException;
12use Wikimedia\ObjectFactory\ObjectFactory;
13
23trait SpecBasedFactoryTrait {
24
28 protected string $langCode;
29
30 protected ?LoggerInterface $logger = null;
31
37 protected array $singletons = [];
38
44 abstract protected function getSpecMap(): array;
45
56 abstract protected function getSpecArgs( array $spec, LoggerInterface $logger ): array;
57
69 protected function createFromSpec( string $class ) {
70 if ( isset( $this->singletons[$class] ) ) {
72 $cached = $this->singletons[$class];
73
74 return $cached;
75 }
76
77 $specs = $this->getSpecMap();
78 if ( !isset( $specs[$class] ) ) {
79 throw new UnexpectedValueException( "Class not registered: $class" );
80 }
81
82 $spec = $specs[$class];
83 $logger = $this->logger ?? new NullLogger();
84
85 $args = $this->getSpecArgs( $spec, $logger );
86 if ( !empty( $spec['args'] ) && is_array( $spec['args'] ) ) {
87 $args = array_merge( $args, $spec['args'] );
88 }
89
91 'class' => $class,
92 'args' => $args,
93 ];
94
95 $instance = ObjectFactory::getObjectFromSpec( $objectSpec );
96
97 if ( !$instance instanceof $class ) {
98 throw new UnexpectedValueException(
99 "Expected instance of $class, got " . get_class( $instance )
100 );
101 }
102
103 $this->singletons[$class] = $instance;
104
105 return $instance;
106 }
107}
if(!isset( $specs[$class])) $spec
array array< string, $singletons=[];abstract protected function getSpecMap():array;abstract protected function getSpecArgs(array $spec, LoggerInterface $logger):array;protected function createFromSpec(string $class) { if(isset($this->singletons[ $class])) { $cached=$this-> singletons[$class]
Cache of created singleton objects.
if(!empty( $spec['args']) &&is_array( $spec['args'])) $objectSpec