stefanbauer's avatar

Getting the Service Container

Some of you know, that i am not a big fan of the Facades. Anyways.. I try to avoid using them where ever it is possible. Is it somehow possible to get the service container within a "regular" class? No controller, no event listener.. I just would like to get a service out of the container without using App::make(). (Dependency Injection in the constructor is not the topic here :)). Just interested in something like...

$this->getContainer()->make('bla');

Is there are trait for it? Or something like a ContainerAware? If not, no problem. I would create it by myself, Just wanted to know if there is something by default :)

0 likes
8 replies
stefanbauer's avatar

Thanks. I just "read it" quickly. All examples are clear. I would not go with the solution to extend from a parent class which injects the container in the constructor. Then i have always to call parent construct if i use it in a child class.. I could go with the method injection like there is a method getContainer() and inject it there. But when the day ends.. the question i ask myself.. why the hack do i need that? :-D As i said, was just a question it asked myself.. I don't see any case where this makes sense, does it?

bestmomo's avatar

I always inject dependency when it's possible and it's quite always the case, otherwise I just use $this->app->make('foo'); depending on context.

stefanbauer's avatar

Yeah! But $this->app is not everywhere available :-) That's why i was asking :-D

bestmomo's avatar

The app helper is always available : app('foo') ;)

And if you dont like helpers you always can do \Illuminate\Container\Container::getInstance()->make('foo')

stefanbauer's avatar

yeah, but this helper stuff looks so strange. It remembers me some years back when coding php :-D Best would be if there is something like $this->getService('foo') or something.. would be no problem to implement in a superclass, but as i said.. i ask myself, why to do that. You said, you use sometimes $this->app->make('foo') depending on context. What is your context, when you use that, instead of DI in the constructor?

bestmomo's avatar

When I say "depending on context" it's for syntax, $this->app->make('foo') will work in route file for example, or in service provider, but not in some helper file.

stefanbauer's avatar

Ah okay :-) Thought you mean with "context" you sometimes use DI in constructer and sometimes not :)

Please or to participate in this conversation.