Skip to content

Commit

Permalink
[5.4] Use Instance instead of Deferred Provider (#20714)
Browse files Browse the repository at this point in the history
* Use Instance instead of Deferred Provider

When calling app()->instance('foo','bar'), if there's a deferred service provider registered for class foo,
the deferred provider gets called and overrides the instance that was just set.  This means that if you have

app()->bind('foo','foo); // in a deferred service provider

and you run the following as the first reference to 'foo'

app()->instance('foo','bar');
$instance = app()->make('foo');

$instance = 'foo' instead of 'bar'

Added an additional condition to Application->make to check to see if an instance for that $abstract as already been set and skip loading the deferred provider if it does.

* Fix style
  • Loading branch information
Hariador authored and taylorotwell committed Aug 24, 2017
1 parent 698b2d2 commit 9a32fb5
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Illuminate/Foundation/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -714,7 +714,7 @@ public function make($abstract, array $parameters = [])
{
$abstract = $this->getAlias($abstract);

if (isset($this->deferredServices[$abstract])) {
if (isset($this->deferredServices[$abstract]) && ! isset($this->instances[$abstract])) {
$this->loadDeferredProvider($abstract);
}

Expand Down
9 changes: 9 additions & 0 deletions tests/Foundation/FoundationApplicationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,15 @@ public function testDeferredServiceProviderIsRegisteredOnlyOnce()
$this->assertEquals(1, ApplicationDeferredServiceProviderCountStub::$count);
}

public function testDeferredServiceDontRunWhenInstanceSet()
{
$app = new Application;
$app->setDeferredServices(['foo' => 'Illuminate\Tests\Foundation\ApplicationDeferredServiceProviderStub']);
$app->instance('foo', 'bar');
$instance = $app->make('foo');
$this->assertEquals($instance, 'bar');
}

public function testDeferredServicesAreLazilyInitialized()
{
ApplicationDeferredServiceProviderStub::$initialized = false;
Expand Down

0 comments on commit 9a32fb5

Please sign in to comment.