跳到內容

如何將實例注入容器

編輯此頁面

在某些應用程式中,您可能需要注入類別實例作為服務,而不是設定容器來建立新的實例。

例如,Symfony 中的 kernel 服務是從 Kernel 類別內部注入到容器中的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// ...
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\HttpKernel\TerminableInterface;

abstract class Kernel implements KernelInterface, TerminableInterface
{
    // ...

    protected function initializeContainer(): void
    {
        // ...
        $this->container->set('kernel', $this);

        // ...
    }
}

在執行時期設定的服務稱為合成服務。此服務必須經過設定,以便容器在編譯期間知道該服務存在(否則,依賴 kernel 的服務將會收到「服務不存在」錯誤)。

為了做到這一點,請在您的服務定義設定中將服務標記為合成服務

1
2
3
4
5
# config/services.yaml
services:
    # synthetic services don't specify a class
    app.synthetic_service:
        synthetic: true

現在,您可以使用 Container::set() 將實例注入到容器中

1
2
3
// instantiate the synthetic service
$theService = ...;
$container->set('app.synthetic_service', $theService);
本作品,包括程式碼範例,以 Creative Commons BY-SA 3.0 授權條款發布。
目錄
    版本