Design Patterns PHP - Dependency Injection Java

1) Ok what have we done ?

Now we just can pass all fields values by constructors


class ClassA
{

    /**
     * @var ClassB
     */
    private $classB;

    /**
     * @var String
     */
    private $one;

    /**
     * @var String
     */
    private $two;

    /**
     * @param ClassB $classB
     * @param String $one
     * @param String $two
     */
    public function __construct($classB, $one, $two)
    {
        $this->classB = $classB;
        $this->one = $one;
        $this->two = $two;
    }

}

class ClassB
{
    /**
     * @var String
     */
    private $one;

    /**
     * @var String
     */
    private $two;

    /**
     * ClassB constructor.
     * @param String $one
     * @param String $two
     */
    public function __construct($one, $two)
    {
        $this->one = $one;
        $this->two = $two;
    }
}




And let's how we create objects in application:


$classA = new ClassA(new ClassB('B1', 'B2'), 'A1', 'A2');

$classA = new ClassA(new ClassB('B1', 'B2'), 'another A1', 'another A2');




2) Is this solution is good ?

Yes it's really quite good, definitely better than hardcoding in step1.
Yes here we have already injecting dependencies.

But still let's imagine that we have more level dependency than two like here.
Creating objects on client side would be problematic, for example we want to reuse some object like in this example we could reuse "B" instead of creating it two times.

For more levels our hierarchy tree of dependency could be big and creating this on client side could be a nightmare.

3) How we can improve this, let's create special object which responsibility would be creating dependency and in easy way client could access for all defined objects.