Skip to content

Instantly share code, notes, and snippets.

@guiwoda
Last active August 29, 2015 14:11
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 guiwoda/b693b21a5f7e5861439f to your computer and use it in GitHub Desktop.
Save guiwoda/b693b21a5f7e5861439f to your computer and use it in GitHub Desktop.
IoC bindings in Laravel
<?php namespace Acme;
interface IFoo {}
class Foo implements IFoo {}
class Bar {
public function __construct(\Acme\IFoo $foo) {}
}
class Baz {
public function __construct(\Acme\Foo $foo) {}
}
/** @type \Illuminate\Foundation\Application $app */
$app->singleton('foo', function(){ return new \Acme\Foo; });
/**
* As I mapped my \Acme\Foo to the 'foo' string, some DI stuff won't work.
* This is because of how the container resolves classes and interfaces.
*/
// Works because Foo is concrete and doesn't have dependencies
$foo = $app->make(Acme\Foo::class);
// Doesn't work, the interface was never bound to an implementation
// "Acme\IFoo is not instantiable" or something...
$anyFoo = $app->make(Acme\IFoo::class);
// Doesn't work because the container can't resolve IFoo
$bar = $app->make(Acme\Bar::class);
// Works because the container can resolve concretes automatically
$baz = $app->make(Acme\Baz::class);
/**
* Adding the interface binding would solve all of this.
*/
$app->bind(Acme\IFoo::class, Acme\Foo::class);
// new Foo;
$anyFoo = $app->make(Acme\IFoo::class);
// new Bar( new Foo );
$bar = $app->make(Acme\Bar::class);
<?php namespace Acme;
/** Try some of this examples: */
// AuthManager is bound to $app['auth']
class MyAuthAdapter {
public $auth;
public function __construct(AuthManager $auth){ $this->auth = $auth; }
}
// gets the current user (the facade uses $app['auth'])
Auth::getUser();
// Fails to get the current user, as its not a singleton service
App::make(\Acme\MyAuthAdapter::class)->auth->driver()->getUser();
class ValidationAwareStuff {
private $validator;
public function __construct(\Illuminate\Validation\Validator $validator){
$this->validator = $validator;
}
}
// Will fail, TranslatorInterface is not bound
App::make(ValidationAwareStuff::class);
// But the validation factory has a default one tho...
$validator = Validator::make(['some' => 'rules'], ['some' => 'data']);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment