mercredi 3 avril 2019

What's the benefit of Service Provider mode?

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'));
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire