Skip to content

Instantly share code, notes, and snippets.

@awei01
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save awei01/9861436 to your computer and use it in GitHub Desktop.
Save awei01/9861436 to your computer and use it in GitHub Desktop.
Example detailing Laravel ServiceProvider registration error. Refer to this issue: https://github.com/laravel/framework/issues/2760
<?php
return array(
/* truncated */
/* this app.php config file will work because 'bar.dependency' has been registered on the container before
* BrokenFooServiceProvider so that when 'bar.dependency' is being called for, it already exists.
*/
'providers' => array(
'BarDependencyServiceProvider',
'BrokenFooServiceProvider',
),
);
<?php
return array(
/* truncated */
/* this app.php config file will break and throw the ReflectionException because BarDependencySerivceProvider has not
* has not registered the 'bar.dependency' on the container yet.
*/
'providers' => array(
'BrokenFooServiceProvider',
'BarDependencyServiceProvider',
),
);
<?php
use Illuminate\Support\ServiceProvider;
class BarDependencyServiceProvider extends ServiceProvider {
public $defer = true;
public function register()
{
$this->app->bindShared('bar.dependency', function($app) use ($required)
{
return new BarDependency;
});
}
public function provides()
{
return array('bar.dependency');
}
}
<?php
use Illuminate\Support\ServiceProvider;
class BrokenFooServiceProvider extends ServiceProvider {
public $defer = true;
/**
* this function will NOT work and throw following exception:
* {"error":{"type":"ReflectionException","message":"Class bar.dependency does not exist",
* "file":"path\\to\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php","line":485}}
*
*/
public function register()
{
$bar = $this->registerBarClass();
$this->app->bindShared('foo', function($app) use ($bar)
{
return new FooClass($bar);
});
}
protected function registerBarClass()
{
$dependency = $this->app['bar.dependency'];
return new BarClass($dependency);
}
public function provides()
{
return array('foo');
}
}
<?php
use Illuminate\Support\ServiceProvider;
class WorkingFooServiceProvider extends ServiceProvider {
public $defer = true;
/**
* this file will work regardless of how the ServiceProviders are ordered within the app.php config file.
* This is because the registration of BarClass which depends upon 'bar.dependency' is taking place within the closure
* passed to $this->app->bindShared()
*/
public function register()
{
$me = $this;
$this->app->bindShared('foo', function($app) use ($me)
{
$bar = $me->registerBarClass();
return new FooClass($bar);
});
}
public function registerBarClass()
{
$dependency = $this->app['bar.dependency'];
return new BarClass($dependency);
}
public function provides()
{
return array('foo');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment