DI in the API demo app

Hi all.
If I run the API demo app: GitHub - yiisoft/app-api: Yii3 API application template
… And add one argument ServerRequestInterface $request to the _invoke() method in the IndexAction, how does PHP know it should provide instance of HttpSoft\Message\ServerRequest?

I am not able to track the logic.

Thanks for any hints.

PS)
My attempts were:

  • If I try to seach for ServerRequestInterface::class … nothing
  • I tried to search for “implements ServerRequestInterface” it took me to vendor/httpsoft/http-message/src/ServerRequest.php
  • Then I searched for “new ServerRequest” and found it in vendor/httpsoft/http-message/src/ServerRequestFactory.php
  • So I found “ServerRequestFactory::class” in config/web/di/psr17.php
  • … and I need to continue with “ServerRequestFactoryInterface” (see psr17.php)

… but this is not the way how to correctly find where do dependencies come from. Right? There must be a logical way.

1 Like

ServerRequestInterface is a special case handled by Yii’s packages since it’s not defined in the container, is created for each request, and is passed through a number of middleware that can modify it.

Except for a few exceptions, you type-hint on:

  1. Interfaces explicitly defined in the container (direct map of interface => class). These could come either from your config or one of the Yii packages (these are not copied in this case).
  2. Classes. These are either defined in the same map or, if not, the container just tries new MyClass().