Complex classes like ContainerTrait 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 ContainerTrait, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 12 | trait ContainerTrait |
||
| 13 | { |
||
| 14 | /** |
||
| 15 | * @var ContainerInterface|null |
||
| 16 | */ |
||
| 17 | protected $container; |
||
| 18 | |||
| 19 | /** |
||
| 20 | * @var string|null |
||
| 21 | */ |
||
| 22 | protected $containerId; |
||
| 23 | |||
| 24 | /** |
||
| 25 | * Load the container and the key used to get the service. |
||
| 26 | * |
||
| 27 | * @param ContainerInterface $container |
||
| 28 | * @param string $id |
||
| 29 | * |
||
| 30 | * @return self |
||
| 31 | */ |
||
| 32 | public function from(ContainerInterface $container, $id) |
||
| 39 | |||
| 40 | /** |
||
| 41 | * Returns the service from the container. |
||
| 42 | * |
||
| 43 | * @param string $type |
||
| 44 | * @param bool $required |
||
| 45 | * |
||
| 46 | * @return null|mixed |
||
| 47 | */ |
||
| 48 | protected function getFromContainer($type = null, $required = true) |
||
| 66 | } |
||
| 67 |