Php 如何使用大量构造函数实例化类和深层层次结构重构代码?

Php 如何使用大量构造函数实例化类和深层层次结构重构代码?,php,dependency-injection,refactoring,Php,Dependency Injection,Refactoring,我想重构一些代码。看起来是这样的: class Calc { function __construct($product = null) { // original code $this->spec = new Spec(); $this->price = new Price(); $this->motor = new Motor(); $this->drive = new D

我想重构一些代码。看起来是这样的:

class Calc
{
    function __construct($product = null)
    {
        // original code
        $this->spec = new Spec();
        $this->price = new Price();
        $this->motor = new Motor();
        $this->drive = new Drive();
        $this->turbine = new Turbine();
        $this->pump = new Pump();

        // new code:
        if ($product == "S")
            $this->option = new OptionsS();
        else
            $this->option = new Options();
    }
}
$array = array(
    'spec' => new Spec(),
    'price' = new Price(),
    ...
    'option' = (new OptionFactory($product))->returnOption()),
);

$calc = new (Calc($array));


//then
class Calc
{
    function __construct($array)
    {
        // original code
        $this->spec = $array['spec'];
        $this->price = $array['price'];
         ...
        $this->option = $array['option'];
    }
}
我想做的是通过构造函数使用DI将单个类传递给Calc。也就是说,由于所有的
新的
类都是必需的,我正在考虑这样的事情:

class Calc
{
    function __construct($product = null)
    {
        // original code
        $this->spec = new Spec();
        $this->price = new Price();
        $this->motor = new Motor();
        $this->drive = new Drive();
        $this->turbine = new Turbine();
        $this->pump = new Pump();

        // new code:
        if ($product == "S")
            $this->option = new OptionsS();
        else
            $this->option = new Options();
    }
}
$array = array(
    'spec' => new Spec(),
    'price' = new Price(),
    ...
    'option' = (new OptionFactory($product))->returnOption()),
);

$calc = new (Calc($array));


//then
class Calc
{
    function __construct($array)
    {
        // original code
        $this->spec = $array['spec'];
        $this->price = $array['price'];
         ...
        $this->option = $array['option'];
    }
}
我想那会管用的。需要注意的是,还有一个类需要
Calc
。即:

class ProductA extends Product
{
    function __construct() {
        $this->calc        = new Calc();
        $this->tech        = new Tech();
        $this->plot        = new Plot();
        $this->outline    = new Outline();
        ...
        $this->input    = new Input();
    }
}
这将使我与DI模式的DI。我是否只是递归地应用DI,直到一切都结束?有更好的办法吗?我是不是应该把代码放在一边

问题:如何处理具有大量子类和深层层次结构的代码(例如,一个3-4层的类树,每个类在构造函数中实例化了大约4-5个类)。我最初的想法是使用DI,“简化它”,但看看为DI重构所涉及的所有工作,看看我们如何在DI上使用DI,我不确定是否值得

我正在寻找更好的方法来重构这样的代码