0

As I understand laravel's service container is for dependency injection.

I usually did these injections by use ClassName and constructor in a given class.

Why would I use service container instead?

After spending all day on reading about it I do not see the difference.

divHelper11
  • 1,734
  • 3
  • 13
  • 34
  • 1
    By doing `use ClassName` you're not injecting anything, you're only helping PHP find the target class when you do `new ClassName`. Namespaces have nothing to do with dependency injection in this context. Read [the docs](https://www.php.net/manual/en/language.namespaces.basics.php) carefully. – Alex Karshin May 10 '20 at 19:06
  • @AlexKarshin Sounds like I am confusing something. Thank you for pointing this out – divHelper11 May 10 '20 at 19:07

2 Answers2

1

If you are type hinting dependencies in controllers constructor you are already using dependency injection and Laravel service container.

There are a lot of good articles and docs about Laravel service container and dependency injection.

I recommend these:

Another StackOverflow question

Laravel Docs Service Container

Laravel Docs Dependency Injection

  • I have been reading all day about Service Containers. Looks like I did not understand correctly what dependency injection actually was. Thank you for linking this – divHelper11 May 10 '20 at 19:24
  • No, problem. It is one of the advanced things so you should take some time to fully understand how Laravel service container works, step by step – Aleksandar Milivojsa May 10 '20 at 20:01
0

PHP type-hinting is not specifically bound to the dependency injection, it's just a PHP feature which allows it thanks to API reflection.

There is at least 1 thing you can't do except via constructor: the contextual binding.

And another one which can't be done via constructor: partial resolution (i.e. app(Test::class, ['arg2' => 'test'])

Also notice that dependency injection can work on every method, not only constructor (e.g. app()->call([$this, 'injectedMethod']) )

Finally, you should read this doc which explains very clearly everything the container is able to.

https://gist.github.com/davejamesmiller/bd857d9b0ac895df7604dd2e63b23afe

Shizzen83
  • 2,711
  • 2
  • 5
  • 28