How are Laravel container binding mechanisms different?

I look at Laravel utility docs containers , in particular the binding section.

What are the differences and when should I use each type of binding? The documentation mentions:

  • Simple snap
  • Syntax binding
  • Linking instances
  • Primitive binding
  • Interface binding
+4
source share
1 answer

First, let's see what it really is:

An IoC container is a component that knows how to instantiate. He also knows about all of his dependent dependencies and how to solve them.

. Laravel API , .

" " - , /. , - [] , .

, :
Laravel IoC Container ?

app()->bind(DatabaseWriter::class, function ($app) {
    return new DatabaseWriter(
        $app->make(DatabaseAdapterInterface)
    );
});

, , DatabaseWriter, , , coz . , , .

. , .

, , . , . , , , , , , . , .

, ? singleton , .

, , Singleton. .

. , , . .

, . mock - , app()->make() . , , .

class QuestionsControllerTest extends TestCase 
{  
    public function testQuestionListing()
    {
        $questionMock = Mockery::mock('Question')
           ->shouldReceive('latest')
           ->once()
           ->getMock();

        // You're telling the container that everytime anyone
        // wants a Question instance, give them this mock I just
        // gave you.
        $this->app->instance('Question', $this->questionMock);

        // whatever...
    }
}

Laravel DSL, , . , BillingController $taxRate, , 0.2. !

app()->when('App\Http\Controllers\BillingController')
     ->needs('$taxRate')
     ->give(.2);

, . :

app()->when('App\Http\Controllers\CustomerController')
    ->needs('$customers')
    ->give(function() {
        return Customer::paying();
    });

, .

SOLID , , , , .

, , .

class DatabaseWriter {

    protected $db;

    // Any concrete implementation of this interface will do
    // Now, that I depend on this DatabaseAdapterInterface contract,
    // I can work with MySQL, MongoDB and WhatevaDB! Awesome!
    public function __construct(DatabaseAdapterInterface $db)
    {
        $this->db = $db;
    }

    public function write()
    {
        $this->db->query('...');
    }

}

Laravel DatabaseAdapterInterface DatabaseWriter, :

$dbWriter = new DatabaseWriter(new MongodbAdapter)

MongodbAdapter , :

// Looks familiar, right? 
// These are those recipes you used to give to Laravel container 
// through simple binding. 
$dbWriter = new DatabaseWriter(new MongodbAdapter(new MongodbConnection))

Laravel , , - DatabaseAdapterInterface, MongodbAdapter:

app()->bind(DatabaseAdapterInterface::class, MongodbAdapter::class)

DatabaseWriter , , boss:

$dbWriter = app()->make(DatabaseWriter::class)

, ? . , AppServiceProvider.

, , . -, DatabaseWriter ( reflection), , DatabaseAdapterInterface. , , , MongodbAdapter - . DatabaseWriter.

, .

, , , :
https://github.com/laravel/framework/blob/5.3/src/Illuminate/Container/Container.php#L627

+6

Source: https://habr.com/ru/post/1661727/


All Articles