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
33 protected ?LoggerInterface $logger = null;
34
40 protected array $singletons = [];
41
47 abstract protected function getSpecMap(): array;
48
59 abstract protected function getSpecArgs( array $spec, LoggerInterface $logger ): array;
60
72 protected function createFromSpec( string $class ) {
73 if ( isset( $this->singletons[$class] ) ) {
75 $cached = $this->singletons[$class];
76
77 return $cached;
78 }
79
80 $specs = $this->getSpecMap();
81 if ( !isset( $specs[$class] ) ) {
82 throw new UnexpectedValueException( "Class not registered: $class" );
83 }
84
85 $spec = $specs[$class];
86 $logger = $this->logger ?? new NullLogger();
87
88 $args = $this->getSpecArgs( $spec, $logger );
89 if ( !empty( $spec['args'] ) && is_array( $spec['args'] ) ) {
90 $args = array_merge( $args, $spec['args'] );
91 }
92
94 'class' => $class,
95 'args' => $args,
96 ];
97
98 $instance = ObjectFactory::getObjectFromSpec( $objectSpec );
99
100 if ( !$instance instanceof $class ) {
101 throw new UnexpectedValueException(
102 "Expected instance of $class, got " . get_class( $instance )
103 );
104 }
105
106 $this->singletons[$class] = $instance;
107
108 return $instance;
109 }
110}
if(!isset( $specs[$class])) $spec
LoggerInterface $logger
The logger instance.
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