0

before anything, l have saw lots of code to prove the service provider, but l still have some problem

the example code:

<?php

namespace App\Http\Controllers\Test;


use App\Http\Controllers\Controller;

class Test extends Controller
{
    // simple case
    public function __construct(\SomeClass $class)
    {
        $this->class = $class;
    }
    // vs
    public function __construct()
    {
        $this->class = new \SomeClass();
    }

most of code l saw said if class is complex:

    public function __construct()
    {
        $this->class = new \SomeClass(new Bar(), new Foo('other dependence'));
    }
    // then they said provider can solve it like:
    $this->app->bind('SomeClass', function(){
        return new \SomeClass(new Bar(), new Foo('other dependence'));
    });
    // and use like follow:
    public function __construct(\SomeClass $class)
    {
        $this->class = $class;
    }

}

So my question is :

if the class is necessary to get instance

why not to do the same things (new a instance) in SomeClass, Bar and Foo like:

class SomeClass
{
    public function __construct()
    {
        $this->bar = new Bar();
        $this->foo = new Foo();
    }
}

class Bar
{
    public function __construct()
    {
    }
}

class Foo
{
    public function __construct()
    {
        $this->other_dep = new OtherDependence();
    }
}

then, l still can code like the first written:

public function __construct()
{
    $this->class = new \SomeClass();
    // now it's equal to
    // $this->class = new \SomeClass(new Bar(), new Foo('other dependence'));
}
afraid.jpg
  • 965
  • 2
  • 14
  • 31
  • Possible duplicate of [Why does one use dependency injection?](https://stackoverflow.com/questions/14301389/why-does-one-use-dependency-injection) – Dees Oomens Apr 04 '19 at 06:36

1 Answers1

0

In the case of $this->app->bind this will tell Laravel how to create an instance of the class when you relsove it from a contsructor __construct(\SomeClass $class) or app('SomeClass') or resolve('SomeClass'). If you don't have some complex dependencies for the class, I would stick to $this->class = new \SomeClass();, because SomeClass doesn't need any other objects to be created. When you do __construct(\SomeClass $class) this will automatically resolve any dependencies which are simple enough for Laravel to figure on itself, e.g. class names, not interfaces.

thefallen
  • 9,496
  • 2
  • 34
  • 49