Search code examples
phplaravellaravel-5.3

Which classes can I type-hint dependencies for automatic injection in Laravel 5?


Laravel's service container has a really great automatic injection feature that allows you to type-hint dependencies in a class constructor (which resolve with a new instance of that dependency if none is provided). I tried doing this in the constructor of an Eloquent model but it failed. After some searching, I realized that there are only certain classes that will be read by the service container. According to the 5.3 docs

Alternatively, and importantly, you may simply "type-hint" the dependency in the constructor of a class that is resolved by the container, including controllers, event listeners, queue jobs, middleware, and more.

It's that last "and more" that makes me curious - does anyone know a complete list of classes where you can type-hint dependencies in Laravel?


Solution

  • The sentence in question is a big part of the list of classes that the framework will resolves via the IoC container or call a method on via the IoC container (method injection). The 'and more' just means they didn't list every possible type of class. Going through the documentation you can find other pages that make mention of the IoC container being used to resolve a particular type of class/call a method. (Artisan Commands and Service Providers for example). The ones that you interact with the most, are documented in their corresponding pages/sections.

    With out going through the framework's container calls, I would say that gathering the list from through-out the docs is probably about it.

    That list of classes are kinda the junction points between your code and the framework itself. To allow you to easily have the dependencies you need, these are resolved/called by the container. Since this process is recursive, this provides injection for all classes resolved because of this.

    About resolving in general:

    Any class can be resolved from the container without any bindings if it doesn't depend upon interfaces.

    To have dependencies injected for you, the IoC container has to be used to do the resolving/calling.

    Dependencies are resolved recursively.