1

I know how an Inversion of Control container works and I know how to create one myself. But I only know how to do this by utilizing register and resolve methods.

I have looked in the Laravel documentation but I am stuck on trying to figure out how Laravel can resolve a dependency based on typehinting. Where is the missing link for this exact part?

When I am using a more traditional IoC container where I manually resolve stuff, I at least have to call a static method to get going. Laravel does not seem to need any of this.

Can somebody steer me in the right direction or set up a tiny example?

I have worked my way through:

http://code.tutsplus.com/tutorials/dependency-injection-huh--net-26903

As a recap. Maybe somebody could set up a quick example with automatic resolution for typehinting or is this really complex?

Stephan-v
  • 19,255
  • 31
  • 115
  • 201
  • 1
    Per your question, it looks like you want to know how Laravel resolves DI through type hint. What you're looking for is called Reflection in PHP. With reflection, you create a mirror object of a class inside a variable and you can navigate through it before making an instance. – Marco Aurélio Deleu Jul 26 '16 at 00:58
  • How does the reflectionclass fire whenever a typehint is used though? – Stephan-v Jul 26 '16 at 06:03
  • 1
    it's doesn't. If you pay close attention to laravel, you only have DI for classes / methods that Laravel invokes for you. If you instance an object manually you'll see that DI does not save you. – Marco Aurélio Deleu Jul 26 '16 at 11:40

1 Answers1

5

The magic happens in Laravel's Container.php class where dependencies are automatically resolved using reflection.

Only classes that are instantiated or "made" using Laravel's DI container will benefit from its dependency injection functionality.

David Smith
  • 593
  • 2
  • 10
  • I'm guessing all controllers are simply being instantiated based on the router that receives a url and controller name. Where does this part happen though? The actually "new up" statement for a controller instance. Also at what point does a controller link with the container so that it might use the reflection from the container? – Stephan-v Jul 28 '16 at 07:35
  • This all happens in the `build()` method. All classes that are built by Laravel's DI container are constructed inside this method. There are 2 return points within this method. The first is at [line 761](https://github.com/laravel/framework/blob/5.2/src/Illuminate/Container/Container.php#L761) where the instantiated object is created using the `new` keyword if the class does not have a `__construct()` method defined. The second return point is [line 779](https://github.com/laravel/framework/blob/5.2/src/Illuminate/Container/Container.php#L779) where the class is instantiated with arguments. – David Smith Jul 28 '16 at 18:37