alpha's avatar
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?

0 likes
5 replies
alpha's avatar
Level 7

@primordial I know dependency injection

what's the use of instance() what kind of scenario?

app()->instance('someClass');

we can just

app()->bind()
martinbean's avatar
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
alpha's avatar
Level 7

@martinbean oh, so with instance() we can easily bind an object (existing instance) on the fly

Please or to participate in this conversation.