Hi, you can use a closure to define the dependency resolution, Here is an example:
class Foo {
public $bar;
}
//binding
App::bind('Foo',function($app,$val)
{
$instance = new Foo();
$instance->bar = $val;
return $instance;
});
Now after the binding you can resolve the Foo
class:
$instance1 = App::make('Foo',10);
$instance2 = App::make('Foo',20);
echo $instance1->bar; //10
echo $instance2->bar; //20;
Regards,
Thank you for the solution but is there no way to do that with type hinting in the controller ?
You can use multiple bindings I think... wait let me check it. Hmm may be something like this would work:
class CurrencyServiceProvider extends ServiceProvider {
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->bind('FooInstance1',function()
{
$instance = new Foo();
//further logic here.
return $instance;
});
$this->app->bind('FooInstance2',function()
{
$instance = new Foo();
//further logic here.
return $instance;
});
}
}
Now you can type hint dependencies like this:
class SomeController extends BaseController{
public function __construct(FooInstance1 $foo1){}
}
class SomeController extends BaseController{
public function __construct(FooInstance2 $foo2){}
//method injection
public function someAction(FooInstance1 $foo1)
{
}
}
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community