Last active
August 29, 2015 14:11
-
-
Save guiwoda/b693b21a5f7e5861439f to your computer and use it in GitHub Desktop.
IoC bindings in Laravel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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