Dependency Injection
Jan 24, 2017
5
Level 7
What's the use of Service Container - Binding Instances?
hey guys, what's the use of Laravel Service Container - Binding Instances?
"You may also bind an existing object instance into the container using the instance method"
I don't really get it, in what case would we want to bind the instance method to a service container?
Level 80
@alpha Adding an instance of something to the container.
For example, I have a SaaS application that looks up an account based on the hostname being used to access the application. As I have a model instance, I can just bind that so I can access the domain/account in other parts of my application:
if (! $this->app->runningInConsole()) {
$domain = Domain::with('account')
->whereName($this->app['request']->getHost())
->firstOrFail();
$this->app->instance(Domain::class, $domain);
$this->app->instance(Account::class, $domain->account);
}
1 like
Please or to participate in this conversation.