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 |
||
| 100 | class Container extends Component |
||
| 101 | { |
||
| 102 | /** |
||
| 103 | * @var array singleton objects indexed by their types |
||
| 104 | */ |
||
| 105 | private $_singletons = []; |
||
| 106 | /** |
||
| 107 | * @var array object definitions indexed by their types |
||
| 108 | */ |
||
| 109 | private $_definitions = []; |
||
| 110 | /** |
||
| 111 | * @var array constructor parameters indexed by object types |
||
| 112 | */ |
||
| 113 | private $_params = []; |
||
| 114 | /** |
||
| 115 | * @var array cached ReflectionClass objects indexed by class/interface names |
||
| 116 | */ |
||
| 117 | private $_reflections = []; |
||
| 118 | /** |
||
| 119 | * @var array cached dependencies indexed by class/interface names. Each class name |
||
| 120 | * is associated with a list of constructor parameter types or default values. |
||
| 121 | */ |
||
| 122 | private $_dependencies = []; |
||
| 123 | |||
| 124 | |||
| 125 | /** |
||
| 126 | * Returns an instance of the requested class. |
||
| 127 | * |
||
| 128 | * You may provide constructor parameters (`$params`) and object configurations (`$config`) |
||
| 129 | * that will be used during the creation of the instance. |
||
| 130 | * |
||
| 131 | * If the class implements [[\yii\base\Configurable]], the `$config` parameter will be passed as the last |
||
| 132 | * parameter to the class constructor; Otherwise, the configuration will be applied *after* the object is |
||
| 133 | * instantiated. |
||
| 134 | * |
||
| 135 | * Note that if the class is declared to be singleton by calling [[setSingleton()]], |
||
| 136 | * the same instance of the class will be returned each time this method is called. |
||
| 137 | * In this case, the constructor parameters and object configurations will be used |
||
| 138 | * only if the class is instantiated the first time. |
||
| 139 | * |
||
| 140 | * @param string $class the class name or an alias name (e.g. `foo`) that was previously registered via [[set()]] |
||
| 141 | * or [[setSingleton()]]. |
||
| 142 | * @param array $params a list of constructor parameter values. The parameters should be provided in the order |
||
| 143 | * they appear in the constructor declaration. If you want to skip some parameters, you should index the remaining |
||
| 144 | * ones with the integers that represent their positions in the constructor parameter list. |
||
| 145 | * @param array $config a list of name-value pairs that will be used to initialize the object properties. |
||
| 146 | * @return object an instance of the requested class. |
||
| 147 | * @throws InvalidConfigException if the class cannot be recognized or correspond to an invalid definition |
||
| 148 | * @throws NotInstantiableException If resolved to an abstract class or an interface (since 2.0.9) |
||
| 149 | */ |
||
| 150 | 2598 | public function get($class, $params = [], $config = []) |
|
| 151 | { |
||
| 152 | 2598 | if (isset($this->_singletons[$class])) { |
|
| 153 | // singleton |
||
| 154 | 2 | return $this->_singletons[$class]; |
|
| 155 | 2598 | } elseif (!isset($this->_definitions[$class])) { |
|
| 156 | 2598 | return $this->build($class, $params, $config); |
|
| 157 | } |
||
| 158 | |||
| 159 | 22 | $definition = $this->_definitions[$class]; |
|
| 160 | |||
| 161 | 22 | if (is_callable($definition, true)) { |
|
| 162 | 3 | $params = $this->resolveDependencies($this->mergeParams($class, $params)); |
|
| 163 | 3 | $object = call_user_func($definition, $this, $params, $config); |
|
| 164 | 22 | } elseif (is_array($definition)) { |
|
| 165 | 22 | $concrete = $definition['class']; |
|
| 166 | 22 | unset($definition['class']); |
|
| 167 | |||
| 168 | 22 | $config = array_merge($definition, $config); |
|
| 169 | 22 | $params = $this->mergeParams($class, $params); |
|
| 170 | |||
| 171 | 22 | if ($concrete === $class) { |
|
| 172 | 1 | $object = $this->build($class, $params, $config); |
|
| 173 | } else { |
||
| 174 | 22 | $object = $this->get($concrete, $params, $config); |
|
| 175 | } |
||
| 176 | 1 | } elseif (is_object($definition)) { |
|
| 177 | 1 | return $this->_singletons[$class] = $definition; |
|
| 178 | } else { |
||
| 179 | throw new InvalidConfigException('Unexpected object definition type: ' . gettype($definition)); |
||
| 180 | } |
||
| 181 | |||
| 182 | 22 | if (array_key_exists($class, $this->_singletons)) { |
|
| 183 | // singleton |
||
| 184 | 1 | $this->_singletons[$class] = $object; |
|
| 185 | } |
||
| 186 | |||
| 187 | 22 | return $object; |
|
| 188 | } |
||
| 189 | |||
| 190 | /** |
||
| 191 | * Registers a class definition with this container. |
||
| 192 | * |
||
| 193 | * For example, |
||
| 194 | * |
||
| 195 | * ```php |
||
| 196 | * // register a class name as is. This can be skipped. |
||
| 197 | * $container->set('yii\db\Connection'); |
||
| 198 | * |
||
| 199 | * // register an interface |
||
| 200 | * // When a class depends on the interface, the corresponding class |
||
| 201 | * // will be instantiated as the dependent object |
||
| 202 | * $container->set('yii\mail\MailInterface', 'yii\swiftmailer\Mailer'); |
||
| 203 | * |
||
| 204 | * // register an alias name. You can use $container->get('foo') |
||
| 205 | * // to create an instance of Connection |
||
| 206 | * $container->set('foo', 'yii\db\Connection'); |
||
| 207 | * |
||
| 208 | * // register a class with configuration. The configuration |
||
| 209 | * // will be applied when the class is instantiated by get() |
||
| 210 | * $container->set('yii\db\Connection', [ |
||
| 211 | * 'dsn' => 'mysql:host=127.0.0.1;dbname=demo', |
||
| 212 | * 'username' => 'root', |
||
| 213 | * 'password' => '', |
||
| 214 | * 'charset' => 'utf8', |
||
| 215 | * ]); |
||
| 216 | * |
||
| 217 | * // register an alias name with class configuration |
||
| 218 | * // In this case, a "class" element is required to specify the class |
||
| 219 | * $container->set('db', [ |
||
| 220 | * 'class' => 'yii\db\Connection', |
||
| 221 | * 'dsn' => 'mysql:host=127.0.0.1;dbname=demo', |
||
| 222 | * 'username' => 'root', |
||
| 223 | * 'password' => '', |
||
| 224 | * 'charset' => 'utf8', |
||
| 225 | * ]); |
||
| 226 | * |
||
| 227 | * // register a PHP callable |
||
| 228 | * // The callable will be executed when $container->get('db') is called |
||
| 229 | * $container->set('db', function ($container, $params, $config) { |
||
| 230 | * return new \yii\db\Connection($config); |
||
| 231 | * }); |
||
| 232 | * ``` |
||
| 233 | * |
||
| 234 | * If a class definition with the same name already exists, it will be overwritten with the new one. |
||
| 235 | * You may use [[has()]] to check if a class definition already exists. |
||
| 236 | * |
||
| 237 | * @param string $class class name, interface name or alias name |
||
| 238 | * @param mixed $definition the definition associated with `$class`. It can be one of the following: |
||
| 239 | * |
||
| 240 | * - a PHP callable: The callable will be executed when [[get()]] is invoked. The signature of the callable |
||
| 241 | * should be `function ($container, $params, $config)`, where `$params` stands for the list of constructor |
||
| 242 | * parameters, `$config` the object configuration, and `$container` the container object. The return value |
||
| 243 | * of the callable will be returned by [[get()]] as the object instance requested. |
||
| 244 | * - a configuration array: the array contains name-value pairs that will be used to initialize the property |
||
| 245 | * values of the newly created object when [[get()]] is called. The `class` element stands for the |
||
| 246 | * the class of the object to be created. If `class` is not specified, `$class` will be used as the class name. |
||
| 247 | * - a string: a class name, an interface name or an alias name. |
||
| 248 | * @param array $params the list of constructor parameters. The parameters will be passed to the class |
||
| 249 | * constructor when [[get()]] is called. |
||
| 250 | * @return $this the container itself |
||
| 251 | */ |
||
| 252 | 414 | public function set($class, $definition = [], array $params = []) |
|
| 259 | /** |
||
| 260 | * Registers a class definition with this container and marks the class as a singleton class. |
||
| 261 | * |
||
| 262 | * This method is similar to [[set()]] except that classes registered via this method will only have one |
||
| 263 | * instance. Each time [[get()]] is called, the same instance of the specified class will be returned. |
||
| 264 | * |
||
| 265 | * @param string $class class name, interface name or alias name |
||
| 266 | * @param mixed $definition the definition associated with `$class`. See [[set()]] for more details. |
||
| 267 | * @param array $params the list of constructor parameters. The parameters will be passed to the class |
||
| 268 | * constructor when [[get()]] is called. |
||
| 269 | * @return $this the container itself |
||
| 270 | * @see set() |
||
| 271 | */ |
||
| 272 | 1 | public function setSingleton($class, $definition = [], array $params = []) |
|
| 273 | { |
||
| 274 | 1 | $this->_definitions[$class] = $this->normalizeDefinition($class, $definition); |
|
| 275 | 1 | $this->_params[$class] = $params; |
|
| 276 | 1 | $this->_singletons[$class] = null; |
|
| 277 | 1 | return $this; |
|
| 278 | } |
||
| 279 | |||
| 280 | /** |
||
| 281 | * Returns a value indicating whether the container has the definition of the specified name. |
||
| 282 | * @param string $class class name, interface name or alias name |
||
| 283 | * @return bool whether the container has the definition of the specified name.. |
||
| 284 | * @see set() |
||
| 285 | */ |
||
| 286 | public function has($class) |
||
| 287 | { |
||
| 288 | return isset($this->_definitions[$class]); |
||
| 289 | } |
||
| 290 | |||
| 291 | /** |
||
| 292 | * Returns a value indicating whether the given name corresponds to a registered singleton. |
||
| 293 | * @param string $class class name, interface name or alias name |
||
| 294 | * @param bool $checkInstance whether to check if the singleton has been instantiated. |
||
| 295 | * @return bool whether the given name corresponds to a registered singleton. If `$checkInstance` is true, |
||
| 296 | * the method should return a value indicating whether the singleton has been instantiated. |
||
| 297 | */ |
||
| 298 | public function hasSingleton($class, $checkInstance = false) |
||
| 299 | { |
||
| 300 | return $checkInstance ? isset($this->_singletons[$class]) : array_key_exists($class, $this->_singletons); |
||
| 301 | } |
||
| 302 | |||
| 303 | /** |
||
| 304 | * Removes the definition for the specified name. |
||
| 305 | * @param string $class class name, interface name or alias name |
||
| 306 | */ |
||
| 307 | public function clear($class) |
||
| 308 | { |
||
| 309 | unset($this->_definitions[$class], $this->_singletons[$class]); |
||
| 310 | } |
||
| 311 | |||
| 312 | /** |
||
| 313 | * Normalizes the class definition. |
||
| 314 | * @param string $class class name |
||
| 315 | * @param string|array|callable $definition the class definition |
||
| 316 | * @return array the normalized class definition |
||
| 317 | * @throws InvalidConfigException if the definition is invalid. |
||
| 318 | */ |
||
| 319 | 415 | protected function normalizeDefinition($class, $definition) |
|
| 320 | { |
||
| 321 | 415 | if (empty($definition)) { |
|
| 322 | 1 | return ['class' => $class]; |
|
| 323 | 415 | } elseif (is_string($definition)) { |
|
| 324 | 4 | return ['class' => $definition]; |
|
| 325 | 414 | } elseif (is_callable($definition, true) || is_object($definition)) { |
|
| 326 | 396 | return $definition; |
|
| 327 | 20 | } elseif (is_array($definition)) { |
|
| 328 | 20 | if (!isset($definition['class'])) { |
|
| 329 | if (strpos($class, '\\') !== false) { |
||
| 330 | $definition['class'] = $class; |
||
| 331 | } else { |
||
| 332 | throw new InvalidConfigException('A class definition requires a "class" member.'); |
||
| 333 | } |
||
| 334 | } |
||
| 335 | |||
| 336 | 20 | return $definition; |
|
| 337 | } |
||
| 338 | |||
| 339 | throw new InvalidConfigException("Unsupported definition type for \"$class\": " . gettype($definition)); |
||
| 340 | } |
||
| 341 | |||
| 342 | /** |
||
| 343 | * Returns the list of the object definitions or the loaded shared objects. |
||
| 344 | * @return array the list of the object definitions or the loaded shared objects (type or ID => definition or instance). |
||
| 345 | */ |
||
| 346 | public function getDefinitions() |
||
| 350 | |||
| 351 | /** |
||
| 352 | * Creates an instance of the specified class. |
||
| 353 | * This method will resolve dependencies of the specified class, instantiate them, and inject |
||
| 354 | * them into the new instance of the specified class. |
||
| 355 | * @param string $class the class name |
||
| 356 | * @param array $params constructor parameters |
||
| 357 | * @param array $config configurations to be applied to the new instance |
||
| 358 | * @return object the newly created instance of the specified class |
||
| 359 | * @throws NotInstantiableException If resolved to an abstract class or an interface (since 2.0.9) |
||
| 360 | */ |
||
| 361 | 2598 | protected function build($class, $params, $config) |
|
| 391 | |||
| 392 | /** |
||
| 393 | * Merges the user-specified constructor parameters with the ones registered via [[set()]]. |
||
| 394 | * @param string $class class name, interface name or alias name |
||
| 395 | * @param array $params the constructor parameters |
||
| 396 | * @return array the merged parameters |
||
| 397 | */ |
||
| 398 | 22 | protected function mergeParams($class, $params) |
|
| 413 | |||
| 414 | /** |
||
| 415 | * Returns the dependencies of the specified class. |
||
| 416 | * @param string $class class name, interface name or alias name |
||
| 417 | * @return array the dependencies of the specified class. |
||
| 418 | */ |
||
| 419 | 2598 | protected function getDependencies($class) |
|
| 447 | |||
| 448 | /** |
||
| 449 | * Resolves dependencies by replacing them with the actual object instances. |
||
| 450 | * @param array $dependencies the dependencies |
||
| 451 | * @param ReflectionClass $reflection the class reflection associated with the dependencies |
||
| 452 | * @return array the resolved dependencies |
||
| 453 | * @throws InvalidConfigException if a dependency cannot be resolved or if a dependency cannot be fulfilled. |
||
| 454 | */ |
||
| 455 | 2595 | protected function resolveDependencies($dependencies, $reflection = null) |
|
| 471 | |||
| 472 | /** |
||
| 473 | * Invoke a callback with resolving dependencies in parameters. |
||
| 474 | * |
||
| 475 | * This methods allows invoking a callback and let type hinted parameter names to be |
||
| 476 | * resolved as objects of the Container. It additionally allow calling function using named parameters. |
||
| 477 | * |
||
| 478 | * For example, the following callback may be invoked using the Container to resolve the formatter dependency: |
||
| 479 | * |
||
| 480 | * ```php |
||
| 481 | * $formatString = function($string, \yii\i18n\Formatter $formatter) { |
||
| 482 | * // ... |
||
| 483 | * } |
||
| 484 | * Yii::$container->invoke($formatString, ['string' => 'Hello World!']); |
||
| 485 | * ``` |
||
| 486 | * |
||
| 487 | * This will pass the string `'Hello World!'` as the first param, and a formatter instance created |
||
| 488 | * by the DI container as the second param to the callable. |
||
| 489 | * |
||
| 490 | * @param callable $callback callable to be invoked. |
||
| 491 | * @param array $params The array of parameters for the function. |
||
| 492 | * This can be either a list of parameters, or an associative array representing named function parameters. |
||
| 493 | * @return mixed the callback return value. |
||
| 494 | * @throws InvalidConfigException if a dependency cannot be resolved or if a dependency cannot be fulfilled. |
||
| 495 | * @throws NotInstantiableException If resolved to an abstract class or an interface (since 2.0.9) |
||
| 496 | * @since 2.0.7 |
||
| 497 | */ |
||
| 498 | 9 | public function invoke(callable $callback, $params = []) |
|
| 506 | |||
| 507 | /** |
||
| 508 | * Resolve dependencies for a function. |
||
| 509 | * |
||
| 510 | * This method can be used to implement similar functionality as provided by [[invoke()]] in other |
||
| 511 | * components. |
||
| 512 | * |
||
| 513 | * @param callable $callback callable to be invoked. |
||
| 514 | * @param array $params The array of parameters for the function, can be either numeric or associative. |
||
| 515 | * @return array The resolved dependencies. |
||
| 516 | * @throws InvalidConfigException if a dependency cannot be resolved or if a dependency cannot be fulfilled. |
||
| 517 | * @throws NotInstantiableException If resolved to an abstract class or an interface (since 2.0.9) |
||
| 518 | * @since 2.0.7 |
||
| 519 | */ |
||
| 520 | 10 | public function resolveCallableDependencies(callable $callback, $params = []) |
|
| 577 | |||
| 578 | /** |
||
| 579 | * Registers class definitions within this container. |
||
| 580 | * |
||
| 581 | * @param array $definitions array of definitions. There are two allowed formats of array. |
||
| 582 | * The first format: |
||
| 583 | * - key: class name, interface name or alias name. The key will be passed to the [[set()]] method |
||
| 584 | * as a first argument `$class`. |
||
| 585 | * - value: the definition associated with `$class`. Possible values are described in |
||
| 586 | * [[set()]] documentation for the `$definition` parameter. Will be passed to the [[set()]] method |
||
| 587 | * as the second argument `$definition`. |
||
| 588 | * |
||
| 589 | * Example: |
||
| 590 | * ```php |
||
| 591 | * $container->setDefinitions([ |
||
| 592 | * 'yii\web\Request' => 'app\components\Request', |
||
| 593 | * 'yii\web\Response' => [ |
||
| 594 | * 'class' => 'app\components\Response', |
||
| 595 | * 'format' => 'json' |
||
| 596 | * ], |
||
| 597 | * 'foo\Bar' => function () { |
||
| 598 | * $qux = new Qux; |
||
| 599 | * $foo = new Foo($qux); |
||
| 600 | * return new Bar($foo); |
||
| 601 | * } |
||
| 602 | * ]); |
||
| 603 | * ``` |
||
| 604 | * |
||
| 605 | * The second format: |
||
| 606 | * - key: class name, interface name or alias name. The key will be passed to the [[set()]] method |
||
| 607 | * as a first argument `$class`. |
||
| 608 | * - value: array of two elements. The first element will be passed the [[set()]] method as the |
||
| 609 | * second argument `$definition`, the second one — as `$params`. |
||
| 610 | * |
||
| 611 | * Example: |
||
| 612 | * ```php |
||
| 613 | * $container->setDefinitions([ |
||
| 614 | * 'foo\Bar' => [ |
||
| 615 | * ['class' => 'app\Bar'], |
||
| 616 | * [Instance::of('baz')] |
||
| 617 | * ] |
||
| 618 | * ]); |
||
| 619 | * ``` |
||
| 620 | * |
||
| 621 | * @see set() to know more about possible values of definitions |
||
| 622 | * @since 2.0.11 |
||
| 623 | */ |
||
| 624 | 2 | public function setDefinitions(array $definitions) |
|
| 635 | |||
| 636 | /** |
||
| 637 | * Registers class definitions as singletons within this container by calling [[setSingleton()]]. |
||
| 638 | * |
||
| 639 | * @param array $singletons array of singleton definitions. See [[setDefinitions()]] |
||
| 640 | * for allowed formats of array. |
||
| 641 | * |
||
| 642 | * @see setDefinitions() for allowed formats of $singletons parameter |
||
| 643 | * @see setSingleton() to know more about possible values of definitions |
||
| 644 | * @since 2.0.11 |
||
| 645 | */ |
||
| 646 | 1 | public function setSingletons(array $singletons) |
|
| 657 | } |
||
| 658 |
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: