For example I have a class named User and in its constructor I have a dependency named MyDependency.
MyDependency does not have any dependencies itself so I don't need to bind it to he $app container.
When I instantiate the User class with no constructor parameters, where does laravel know that a constructer is triggered and it must resolve its dependencies?
I know that Service Container uses ReflectionClass to instantiate the Dependency. But there must be some function which gets triggered to perform this.
It doesn't. You have to explicitly call
App::make()to create an instance. The same goes for calling other methods usingApp:call(). Here's the relevant section of the docs: https://laravel.com/docs/10.x/container#the-make-methodUPD Assume the following controller:
The contents of OrderService:
In your service provider you have:
$this->app->when(OrderService::class)->needs('$dry')->give(false);And in your
routes/api.phpRoute::get('/order/{order}', [OrderController::class, 'update']);Now what happens when make a request to
api/order/1? First, theOrderControllerinstance is created. You provided the class name when registering the route, so Laravel knows which class to use. The instances is created with a call ofmake. As you mention in the quetion, reflections are used to determine, what arguments are expected by the constructor. In our case it's just the instance ofOrderService. So now Laravel will try to resolve this dependency. It's a class, not an interface, so Laravel will simply try to create it's instance, again usingmake. Again, analysing the constructor it will determine that it needs boolean parameter$dry. For which we have registered a resolver in our service provider. So$drygets passed to theOrderServiceconstructor, Laravel gets an instance and passes it toOrderControllerconstructor. Now it can call theupdatemethod. By the same logic, thecallmethod is used to resolve all dependencies. In this case it's just model dependency, which Laravel can resolve out of the box.The general idea here is that
makeandcallare always being called somewhere under the hood. There's no mechanism to intercept a native call to constructor or method. For example, if you modifyroutes/api.phplike this:You'll get an ArgumentCountError for the constructor call.