自动注入依赖

Automatically inject dependency

我不明白为什么 Silex\Application 对象被注入到一些 类 而其他人却没有。这是一个例子

示例 1

/
 Controllers
   Admin
     LoginController.php


namespace SD\Controllers\Admin;

use Silex\Application;

class LoginController
{
  public function loginAction(\Silex\Application $app)
  {
     //in this method Application object is injected automatically
  }
}

示例 2

/
 Lib
  RoutesFactory.php

namespace SD\Lib;

use Silex\Application;

class RoutesFactory
{
  public static function make(\Silex\Application $app)
  {
    // in this method Application object is not injected automatically and I get an error saying the object passed to method make is none instead of \Silex\Apllication
  }
}

那么,为什么第一个示例中的 Application 对象会自动注入,而第二个示例中却没有?

硅胶 does parameter conversion in controllers (and in controllers only), so in the controllers methods you can type hint and expect to "automatically" have the instance, but not anywhere else. From the official docs:

You can (in the controller method) use Request and Silex\Application type hints to get $request and $app injected.

注意:强调我的,它是从上下文中提取的,所以我最好把它说清楚。

有关详细信息,请查看 Silex controller resolver code and also the Symfony's HttpKernel one