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();
$this->app->instance('Question', $this->questionMock);
}
}
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;
public function __construct(DatabaseAdapterInterface $db)
{
$this->db = $db;
}
public function write()
{
$this->db->query('...');
}
}
Laravel DatabaseAdapterInterface DatabaseWriter, :
$dbWriter = new DatabaseWriter(new MongodbAdapter)
MongodbAdapter , :
$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