Support the ongoing development of Laravel.io →
posted 9 years ago
IOC
Last updated 1 year ago.
0

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,

Last updated 1 year ago.
0

Thank you for the solution but is there no way to do that with type hinting in the controller ?

Last updated 1 year ago.
0

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)
	{

	}
}
Last updated 1 year ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

mcraz mcraz Joined 12 Feb 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.