Complex classes like Container often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Container, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
101 | class Container extends Component |
||
102 | { |
||
103 | /** |
||
104 | * @var array singleton objects indexed by their types |
||
105 | */ |
||
106 | private $_singletons = []; |
||
107 | /** |
||
108 | * @var array object definitions indexed by their types |
||
109 | */ |
||
110 | private $_definitions = []; |
||
111 | /** |
||
112 | * @var array constructor parameters indexed by object types |
||
113 | */ |
||
114 | private $_params = []; |
||
115 | /** |
||
116 | * @var array cached ReflectionClass objects indexed by class/interface names |
||
117 | */ |
||
118 | private $_reflections = []; |
||
119 | /** |
||
120 | * @var array cached dependencies indexed by class/interface names. Each class name |
||
121 | * is associated with a list of constructor parameter types or default values. |
||
122 | */ |
||
123 | private $_dependencies = []; |
||
124 | |||
125 | |||
126 | /** |
||
127 | * Returns an instance of the requested class. |
||
128 | * |
||
129 | * You may provide constructor parameters (`$params`) and object configurations (`$config`) |
||
130 | * that will be used during the creation of the instance. |
||
131 | * |
||
132 | * If the class implements [[\yii\base\Configurable]], the `$config` parameter will be passed as the last |
||
133 | * parameter to the class constructor; Otherwise, the configuration will be applied *after* the object is |
||
134 | * instantiated. |
||
135 | * |
||
136 | * Note that if the class is declared to be singleton by calling [[setSingleton()]], |
||
137 | * the same instance of the class will be returned each time this method is called. |
||
138 | * In this case, the constructor parameters and object configurations will be used |
||
139 | * only if the class is instantiated the first time. |
||
140 | * |
||
141 | * @param string $class the class name or an alias name (e.g. `foo`) that was previously registered via [[set()]] |
||
142 | * or [[setSingleton()]]. |
||
143 | * @param array $params a list of constructor parameter values. The parameters should be provided in the order |
||
144 | * they appear in the constructor declaration. If you want to skip some parameters, you should index the remaining |
||
145 | * ones with the integers that represent their positions in the constructor parameter list. |
||
146 | * @param array $config a list of name-value pairs that will be used to initialize the object properties. |
||
147 | * @return object an instance of the requested class. |
||
148 | * @throws InvalidConfigException if the class cannot be recognized or correspond to an invalid definition |
||
149 | * @throws NotInstantiableException If resolved to an abstract class or an interface (since 2.0.9) |
||
150 | */ |
||
151 | 3179 | public function get($class, $params = [], $config = []) |
|
152 | { |
||
153 | 3179 | if (isset($this->_singletons[$class])) { |
|
154 | // singleton |
||
155 | 2 | return $this->_singletons[$class]; |
|
156 | 3179 | } elseif (!isset($this->_definitions[$class])) { |
|
157 | 3179 | return $this->build($class, $params, $config); |
|
158 | } |
||
159 | |||
160 | 22 | $definition = $this->_definitions[$class]; |
|
161 | |||
162 | 22 | if (is_callable($definition, true)) { |
|
163 | 3 | $params = $this->resolveDependencies($this->mergeParams($class, $params)); |
|
164 | 3 | $object = call_user_func($definition, $this, $params, $config); |
|
165 | 22 | } elseif (is_array($definition)) { |
|
166 | 22 | $concrete = $definition['class']; |
|
167 | 22 | unset($definition['class']); |
|
168 | |||
169 | 22 | $config = array_merge($definition, $config); |
|
170 | 22 | $params = $this->mergeParams($class, $params); |
|
171 | |||
172 | 22 | if ($concrete === $class) { |
|
173 | 1 | $object = $this->build($class, $params, $config); |
|
174 | } else { |
||
175 | 22 | $object = $this->get($concrete, $params, $config); |
|
176 | } |
||
177 | 1 | } elseif (is_object($definition)) { |
|
178 | 1 | return $this->_singletons[$class] = $definition; |
|
179 | } else { |
||
180 | throw new InvalidConfigException('Unexpected object definition type: ' . gettype($definition)); |
||
181 | } |
||
182 | |||
183 | 22 | if (array_key_exists($class, $this->_singletons)) { |
|
184 | // singleton |
||
185 | 1 | $this->_singletons[$class] = $object; |
|
186 | } |
||
187 | |||
188 | 22 | return $object; |
|
189 | } |
||
190 | |||
191 | /** |
||
192 | * Registers a class definition with this container. |
||
193 | * |
||
194 | * For example, |
||
195 | * |
||
196 | * ```php |
||
197 | * // register a class name as is. This can be skipped. |
||
198 | * $container->set(\yii\db\Connection::class); |
||
199 | * |
||
200 | * // register an interface |
||
201 | * // When a class depends on the interface, the corresponding class |
||
202 | * // will be instantiated as the dependent object |
||
203 | * $container->set(\yii\mail\MailInterface::class, \yii\swiftmailer\Mailer::class); |
||
204 | * |
||
205 | * // register an alias name. You can use $container->get('foo') |
||
206 | * // to create an instance of Connection |
||
207 | * $container->set('foo', \yii\db\Connection::class); |
||
208 | * |
||
209 | * // register a class with configuration. The configuration |
||
210 | * // will be applied when the class is instantiated by get() |
||
211 | * $container->set(\yii\db\Connection::class, [ |
||
212 | * 'dsn' => 'mysql:host=127.0.0.1;dbname=demo', |
||
213 | * 'username' => 'root', |
||
214 | * 'password' => '', |
||
215 | * 'charset' => 'utf8', |
||
216 | * ]); |
||
217 | * |
||
218 | * // register an alias name with class configuration |
||
219 | * // In this case, a "class" element is required to specify the class |
||
220 | * $container->set('db', [ |
||
221 | * 'class' => \yii\db\Connection::class, |
||
222 | * 'dsn' => 'mysql:host=127.0.0.1;dbname=demo', |
||
223 | * 'username' => 'root', |
||
224 | * 'password' => '', |
||
225 | * 'charset' => 'utf8', |
||
226 | * ]); |
||
227 | * |
||
228 | * // register a PHP callable |
||
229 | * // The callable will be executed when $container->get('db') is called |
||
230 | * $container->set('db', function ($container, $params, $config) { |
||
231 | * return new \yii\db\Connection($config); |
||
232 | * }); |
||
233 | * ``` |
||
234 | * |
||
235 | * If a class definition with the same name already exists, it will be overwritten with the new one. |
||
236 | * You may use [[has()]] to check if a class definition already exists. |
||
237 | * |
||
238 | * @param string $class class name, interface name or alias name |
||
239 | * @param mixed $definition the definition associated with `$class`. It can be one of the following: |
||
240 | * |
||
241 | * - a PHP callable: The callable will be executed when [[get()]] is invoked. The signature of the callable |
||
242 | * should be `function ($container, $params, $config)`, where `$params` stands for the list of constructor |
||
243 | * parameters, `$config` the object configuration, and `$container` the container object. The return value |
||
244 | * of the callable will be returned by [[get()]] as the object instance requested. |
||
245 | * - a configuration array: the array contains name-value pairs that will be used to initialize the property |
||
246 | * values of the newly created object when [[get()]] is called. The `class` element stands for the |
||
247 | * the class of the object to be created. If `class` is not specified, `$class` will be used as the class name. |
||
248 | * - a string: a class name, an interface name or an alias name. |
||
249 | * @param array $params the list of constructor parameters. The parameters will be passed to the class |
||
250 | * constructor when [[get()]] is called. |
||
251 | * @return $this the container itself |
||
252 | */ |
||
253 | 530 | public function set($class, $definition = [], array $params = []) |
|
254 | { |
||
255 | 530 | $this->_definitions[$class] = $this->normalizeDefinition($class, $definition); |
|
|
|||
256 | 530 | $this->_params[$class] = $params; |
|
257 | 530 | unset($this->_singletons[$class]); |
|
258 | 530 | return $this; |
|
259 | } |
||
260 | /** |
||
261 | * Registers a class definition with this container and marks the class as a singleton class. |
||
262 | * |
||
263 | * This method is similar to [[set()]] except that classes registered via this method will only have one |
||
264 | * instance. Each time [[get()]] is called, the same instance of the specified class will be returned. |
||
265 | * |
||
266 | * @param string $class class name, interface name or alias name |
||
267 | * @param mixed $definition the definition associated with `$class`. See [[set()]] for more details. |
||
268 | * @param array $params the list of constructor parameters. The parameters will be passed to the class |
||
269 | * constructor when [[get()]] is called. |
||
270 | * @return $this the container itself |
||
271 | * @see set() |
||
272 | */ |
||
273 | 1 | public function setSingleton($class, $definition = [], array $params = []) |
|
274 | { |
||
275 | 1 | $this->_definitions[$class] = $this->normalizeDefinition($class, $definition); |
|
276 | 1 | $this->_params[$class] = $params; |
|
277 | 1 | $this->_singletons[$class] = null; |
|
278 | 1 | return $this; |
|
279 | } |
||
280 | |||
281 | /** |
||
282 | * Returns a value indicating whether the container has the definition of the specified name. |
||
283 | * @param string $class class name, interface name or alias name |
||
284 | * @return bool whether the container has the definition of the specified name.. |
||
285 | * @see set() |
||
286 | */ |
||
287 | public function has($class) |
||
291 | |||
292 | /** |
||
293 | * Returns a value indicating whether the given name corresponds to a registered singleton. |
||
294 | * @param string $class class name, interface name or alias name |
||
295 | * @param bool $checkInstance whether to check if the singleton has been instantiated. |
||
296 | * @return bool whether the given name corresponds to a registered singleton. If `$checkInstance` is true, |
||
297 | * the method should return a value indicating whether the singleton has been instantiated. |
||
298 | */ |
||
299 | public function hasSingleton($class, $checkInstance = false) |
||
303 | |||
304 | /** |
||
305 | * Removes the definition for the specified name. |
||
306 | * @param string $class class name, interface name or alias name |
||
307 | */ |
||
308 | public function clear($class) |
||
312 | |||
313 | /** |
||
314 | * Normalizes the class definition. |
||
315 | * @param string $class class name |
||
316 | * @param string|array|callable $definition the class definition |
||
317 | * @return array the normalized class definition |
||
318 | * @throws InvalidConfigException if the definition is invalid. |
||
319 | */ |
||
320 | 531 | protected function normalizeDefinition($class, $definition) |
|
321 | { |
||
322 | 531 | if (empty($definition)) { |
|
323 | 1 | return ['class' => $class]; |
|
324 | 531 | } elseif (is_string($definition)) { |
|
325 | 4 | return ['class' => $definition]; |
|
326 | 530 | } elseif (is_callable($definition, true) || is_object($definition)) { |
|
327 | 512 | return $definition; |
|
328 | 21 | } elseif (is_array($definition)) { |
|
329 | 21 | if (!isset($definition['class'])) { |
|
330 | if (strpos($class, '\\') !== false) { |
||
331 | $definition['class'] = $class; |
||
332 | } else { |
||
333 | throw new InvalidConfigException('A class definition requires a "class" member.'); |
||
334 | } |
||
335 | } |
||
336 | |||
337 | 21 | return $definition; |
|
338 | } |
||
339 | |||
340 | throw new InvalidConfigException("Unsupported definition type for \"$class\": " . gettype($definition)); |
||
341 | } |
||
342 | |||
343 | /** |
||
344 | * Returns the list of the object definitions or the loaded shared objects. |
||
345 | * @return array the list of the object definitions or the loaded shared objects (type or ID => definition or instance). |
||
346 | */ |
||
347 | public function getDefinitions() |
||
351 | |||
352 | /** |
||
353 | * Creates an instance of the specified class. |
||
354 | * This method will resolve dependencies of the specified class, instantiate them, and inject |
||
355 | * them into the new instance of the specified class. |
||
356 | * @param string $class the class name |
||
357 | * @param array $params constructor parameters |
||
358 | * @param array $config configurations to be applied to the new instance |
||
359 | * @return object the newly created instance of the specified class |
||
360 | * @throws NotInstantiableException If resolved to an abstract class or an interface (since 2.0.9) |
||
361 | */ |
||
362 | 3179 | protected function build($class, $params, $config) |
|
394 | |||
395 | /** |
||
396 | * Merges the user-specified constructor parameters with the ones registered via [[set()]]. |
||
397 | * @param string $class class name, interface name or alias name |
||
398 | * @param array $params the constructor parameters |
||
399 | * @return array the merged parameters |
||
400 | */ |
||
401 | 22 | protected function mergeParams($class, $params) |
|
416 | |||
417 | /** |
||
418 | * Returns the dependencies of the specified class. |
||
419 | * @param string $class class name, interface name or alias name |
||
420 | * @return array the dependencies of the specified class. |
||
421 | */ |
||
422 | 3179 | protected function getDependencies($class) |
|
423 | { |
||
424 | 3179 | if (isset($this->_reflections[$class])) { |
|
425 | 2329 | return [$this->_reflections[$class], $this->_dependencies[$class]]; |
|
426 | } |
||
427 | |||
428 | 1498 | $dependencies = []; |
|
429 | 1498 | $reflection = new ReflectionClass($class); |
|
430 | |||
431 | 1496 | $constructor = $reflection->getConstructor(); |
|
432 | 1496 | if ($constructor !== null) { |
|
433 | 1493 | foreach ($constructor->getParameters() as $param) { |
|
434 | 1493 | if (version_compare(PHP_VERSION, '5.6.0', '>=') && $param->isVariadic()) { |
|
435 | 1 | break; |
|
436 | 1492 | } elseif ($param->isDefaultValueAvailable()) { |
|
437 | 1492 | $dependencies[] = $param->getDefaultValue(); |
|
438 | } else { |
||
439 | 109 | $c = $param->getClass(); |
|
440 | 1492 | $dependencies[] = Instance::of($c === null ? null : $c->getName()); |
|
441 | } |
||
442 | } |
||
443 | } |
||
444 | |||
445 | 1496 | $this->_reflections[$class] = $reflection; |
|
446 | 1496 | $this->_dependencies[$class] = $dependencies; |
|
447 | |||
448 | 1496 | return [$reflection, $dependencies]; |
|
449 | } |
||
450 | |||
451 | /** |
||
452 | * Resolves dependencies by replacing them with the actual object instances. |
||
453 | * @param array $dependencies the dependencies |
||
454 | * @param ReflectionClass $reflection the class reflection associated with the dependencies |
||
455 | * @return array the resolved dependencies |
||
456 | * @throws InvalidConfigException if a dependency cannot be resolved or if a dependency cannot be fulfilled. |
||
457 | */ |
||
458 | 3177 | protected function resolveDependencies($dependencies, $reflection = null) |
|
474 | |||
475 | /** |
||
476 | * Invoke a callback with resolving dependencies in parameters. |
||
477 | * |
||
478 | * This methods allows invoking a callback and let type hinted parameter names to be |
||
479 | * resolved as objects of the Container. It additionally allow calling function using named parameters. |
||
480 | * |
||
481 | * For example, the following callback may be invoked using the Container to resolve the formatter dependency: |
||
482 | * |
||
483 | * ```php |
||
484 | * $formatString = function($string, \yii\i18n\Formatter $formatter) { |
||
485 | * // ... |
||
486 | * } |
||
487 | * Yii::$container->invoke($formatString, ['string' => 'Hello World!']); |
||
488 | * ``` |
||
489 | * |
||
490 | * This will pass the string `'Hello World!'` as the first param, and a formatter instance created |
||
491 | * by the DI container as the second param to the callable. |
||
492 | * |
||
493 | * @param callable $callback callable to be invoked. |
||
494 | * @param array $params The array of parameters for the function. |
||
495 | * This can be either a list of parameters, or an associative array representing named function parameters. |
||
496 | * @return mixed the callback return value. |
||
497 | * @throws InvalidConfigException if a dependency cannot be resolved or if a dependency cannot be fulfilled. |
||
498 | * @throws NotInstantiableException If resolved to an abstract class or an interface (since 2.0.9) |
||
499 | * @since 2.0.7 |
||
500 | */ |
||
501 | 10 | public function invoke(callable $callback, $params = []) |
|
509 | |||
510 | /** |
||
511 | * Resolve dependencies for a function. |
||
512 | * |
||
513 | * This method can be used to implement similar functionality as provided by [[invoke()]] in other |
||
514 | * components. |
||
515 | * |
||
516 | * @param callable $callback callable to be invoked. |
||
517 | * @param array $params The array of parameters for the function, can be either numeric or associative. |
||
518 | * @return array The resolved dependencies. |
||
519 | * @throws InvalidConfigException if a dependency cannot be resolved or if a dependency cannot be fulfilled. |
||
520 | * @throws NotInstantiableException If resolved to an abstract class or an interface (since 2.0.9) |
||
521 | * @since 2.0.7 |
||
522 | */ |
||
523 | 11 | public function resolveCallableDependencies(callable $callback, $params = []) |
|
524 | { |
||
525 | 11 | if (is_array($callback)) { |
|
526 | 2 | $reflection = new \ReflectionMethod($callback[0], $callback[1]); |
|
527 | } else { |
||
528 | 11 | $reflection = new \ReflectionFunction($callback); |
|
529 | } |
||
530 | |||
531 | 11 | $args = []; |
|
532 | |||
533 | 11 | $associative = ArrayHelper::isAssociative($params); |
|
534 | |||
535 | 11 | foreach ($reflection->getParameters() as $param) { |
|
536 | 6 | $name = $param->getName(); |
|
537 | 6 | if (($class = $param->getClass()) !== null) { |
|
538 | 4 | $className = $class->getName(); |
|
539 | 4 | if (version_compare(PHP_VERSION, '5.6.0', '>=') && $param->isVariadic()) { |
|
540 | 1 | $args = array_merge($args, array_values($params)); |
|
541 | 1 | break; |
|
542 | 3 | } elseif ($associative && isset($params[$name]) && $params[$name] instanceof $className) { |
|
543 | $args[] = $params[$name]; |
||
544 | unset($params[$name]); |
||
545 | 3 | } elseif (!$associative && isset($params[0]) && $params[0] instanceof $className) { |
|
546 | 1 | $args[] = array_shift($params); |
|
547 | 3 | } elseif (isset(Yii::$app) && Yii::$app->has($name) && ($obj = Yii::$app->get($name)) instanceof $className) { |
|
548 | 1 | $args[] = $obj; |
|
549 | } else { |
||
550 | // If the argument is optional we catch not instantiable exceptions |
||
551 | try { |
||
552 | 3 | $args[] = $this->get($className); |
|
553 | 1 | } catch (NotInstantiableException $e) { |
|
554 | 1 | if ($param->isDefaultValueAvailable()) { |
|
555 | 1 | $args[] = $param->getDefaultValue(); |
|
556 | } else { |
||
557 | 3 | throw $e; |
|
558 | } |
||
559 | } |
||
560 | } |
||
561 | 4 | } elseif ($associative && isset($params[$name])) { |
|
562 | 2 | $args[] = $params[$name]; |
|
563 | 2 | unset($params[$name]); |
|
564 | 4 | } elseif (!$associative && count($params)) { |
|
565 | 3 | $args[] = array_shift($params); |
|
566 | 3 | } elseif ($param->isDefaultValueAvailable()) { |
|
567 | 3 | $args[] = $param->getDefaultValue(); |
|
568 | 1 | } elseif (!$param->isOptional()) { |
|
569 | $funcName = $reflection->getName(); |
||
570 | 5 | throw new InvalidConfigException("Missing required parameter \"$name\" when calling \"$funcName\"."); |
|
571 | } |
||
572 | } |
||
573 | |||
574 | 11 | foreach ($params as $value) { |
|
575 | $args[] = $value; |
||
576 | } |
||
577 | |||
578 | 11 | return $args; |
|
579 | } |
||
580 | |||
581 | /** |
||
582 | * Registers class definitions within this container. |
||
583 | * |
||
584 | * @param array $definitions array of definitions. There are two allowed formats of array. |
||
585 | * The first format: |
||
586 | * - key: class name, interface name or alias name. The key will be passed to the [[set()]] method |
||
587 | * as a first argument `$class`. |
||
588 | * - value: the definition associated with `$class`. Possible values are described in |
||
589 | * [[set()]] documentation for the `$definition` parameter. Will be passed to the [[set()]] method |
||
590 | * as the second argument `$definition`. |
||
591 | * |
||
592 | * Example: |
||
593 | * ```php |
||
594 | * $container->setDefinitions([ |
||
595 | * 'yii\web\Request' => 'app\components\Request', |
||
596 | * 'yii\web\Response' => [ |
||
597 | * 'class' => 'app\components\Response', |
||
598 | * 'format' => 'json' |
||
599 | * ], |
||
600 | * 'foo\Bar' => function () { |
||
601 | * $qux = new Qux; |
||
602 | * $foo = new Foo($qux); |
||
603 | * return new Bar($foo); |
||
604 | * } |
||
605 | * ]); |
||
606 | * ``` |
||
607 | * |
||
608 | * The second format: |
||
609 | * - key: class name, interface name or alias name. The key will be passed to the [[set()]] method |
||
610 | * as a first argument `$class`. |
||
611 | * - value: array of two elements. The first element will be passed the [[set()]] method as the |
||
612 | * second argument `$definition`, the second one — as `$params`. |
||
613 | * |
||
614 | * Example: |
||
615 | * ```php |
||
616 | * $container->setDefinitions([ |
||
617 | * 'foo\Bar' => [ |
||
618 | * ['class' => 'app\Bar'], |
||
619 | * [Instance::of('baz')] |
||
620 | * ] |
||
621 | * ]); |
||
622 | * ``` |
||
623 | * |
||
624 | * @see set() to know more about possible values of definitions |
||
625 | * @since 2.0.11 |
||
626 | */ |
||
627 | 2 | public function setDefinitions(array $definitions) |
|
638 | |||
639 | /** |
||
640 | * Registers class definitions as singletons within this container by calling [[setSingleton()]]. |
||
641 | * |
||
642 | * @param array $singletons array of singleton definitions. See [[setDefinitions()]] |
||
643 | * for allowed formats of array. |
||
644 | * |
||
645 | * @see setDefinitions() for allowed formats of $singletons parameter |
||
646 | * @see setSingleton() to know more about possible values of definitions |
||
647 | * @since 2.0.11 |
||
648 | */ |
||
649 | 1 | public function setSingletons(array $singletons) |
|
660 | } |
||
661 |
It seems like the type of the argument is not accepted by the function/method which you are calling.
In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.
We suggest to add an explicit type cast like in the following example: