跳到內容

在依賴注入類別中使用參數

編輯此頁面

您已經了解如何在 Symfony 服務容器 中使用組態參數。有些特殊情況,例如當您想要使用 %kernel.debug% 參數來使您套件中的服務進入偵錯模式時。在這種情況下,為了讓系統理解參數值,需要做更多的工作。預設情況下,您的 %kernel.debug% 參數將被視為字串。請看以下範例

1
2
3
4
5
6
7
8
9
10
11
// inside Configuration class
$rootNode
    ->children()
        ->booleanNode('logging')->defaultValue('%kernel.debug%')->end()
        // ...
    ->end()
;

// inside the Extension class
$config = $this->processConfiguration($configuration, $configs);
var_dump($config['logging']);

現在,仔細檢查結果以了解這一點

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
my_bundle:
    logging: true
    # true, as expected

my_bundle:
    logging: '%kernel.debug%'
    # true/false (depends on 2nd argument of the Kernel class),
    # as expected, because %kernel.debug% inside configuration
    # gets evaluated before being passed to the extension

my_bundle: ~
# passes the string "%kernel.debug%".
# Which is always considered as true.
# The Configurator does not know anything about
# "%kernel.debug%" being a parameter.

為了支援這種使用情況,必須通過擴充功能將 Configuration 類別注入此參數,如下所示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
namespace App\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

class Configuration implements ConfigurationInterface
{
    private bool $debug;

    public function __construct(private bool $debug)
    {
    }

    public function getConfigTreeBuilder(): TreeBuilder
    {
        $treeBuilder = new TreeBuilder('my_bundle');

        $treeBuilder->getRootNode()
            ->children()
                // ...
                ->booleanNode('logging')->defaultValue($this->debug)->end()
                // ...
            ->end()
        ;

        return $treeBuilder;
    }
}

並通過 Extension 類別在 Configuration 的建構子中設定它

1
2
3
4
5
6
7
8
9
10
11
12
13
14
namespace App\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

class AppExtension extends Extension
{
    // ...

    public function getConfiguration(array $config, ContainerBuilder $container): Configuration
    {
        return new Configuration($container->getParameter('kernel.debug'));
    }
}

提示

Configurator 類別中,例如在 TwigBundle 中,有一些 %kernel.debug% 的使用範例。然而,這是因為預設參數值是由 Extension 類別設定的。

這項工作,包括程式碼範例,根據 Creative Commons BY-SA 3.0 授權條款授權。
目錄
    版本