如何从symfony2中的控制器中读取parameters.yml?

问题描述 投票:134回答:6

我在app / config / parameters.yml中放了几个自定义变量。

parameters:
    api_pass: apipass
    api_user: apiuser

我需要从我的控制器访问这些,并试图用它来获取它们

$this->get('api_user');

从我的控制器文件中。当我尝试这个时,我收到此错误消息:

You have requested a non-existent service "api_user".

这样做的正确方法是什么?

symfony symfony-2.3
6个回答
285
投票

在Symfony 2.6和更早版本中,要在控制器中获取参数 - 您应首先获取容器,然后获取所需参数。

$this->container->getParameter('api_user');

这个documentation chapter解释了它。

而控制器中的$this->get()方法将加载服务(doc

在Symfony 2.7及更高版本中,要在控制器中获取参数,可以使用以下命令:

$this->getParameter('api_user');

17
投票

The Clean Way

自2017年以来,Symfony 3.3 + 3.4有更清洁的方式 - 易于设置和使用。

您可以通过它的构造函数将参数传递给类,而不是使用容器和服务/参数定位器反模式。别担心,这不是时间要求很高的工作,而是设置一次忘记方法。

如何分两步设置?

1. app/config/services.yml

# config.yml

# config.yml
parameters:
    api_pass: 'secret_password'
    api_user: 'my_name'

services:
    _defaults:
        autowire: true
        bind:
            $apiPass: '%api_pass%'
            $apiUser: '%api_user%'

    App\:
        resource: ..

2.任何Controller

<?php declare(strict_types=1);

final class ApiController extends SymfonyController
{
    /**
     * @var string 
     */
    private $apiPass;

    /**
     * @var string
     */
    private $apiUser;

    public function __construct(string $apiPass, string $apiUser)
    {
        $this->apiPass = $apiPass;
        $this->apiUser = $apiUser;
    }

    public function registerAction(): void
    {
        var_dump($this->apiPass); // "secret_password"
        var_dump($this->apiUser); // "my_name"
    }
}

即时升级就绪!

如果你使用较旧的方法,你可以automate it with Rector

Read More

这称为服务定位器方法的构造函数注入。

要了解更多相关信息,请查看我的帖子How to Get Parameter in Symfony Controller the Clean Way

(经过测试,我保持更新为新的Symfony主要版本(5,6 ...))。


9
投票

我给你发了一个swiftmailer的例子:

parameters.yml

recipients: [email1, email2, email3]

服务:

your_service_name:
        class: your_namespace
        arguments: ["%recipients%"]

服务类:

protected $recipients;

public function __construct($recipients)
{
    $this->recipients = $recipients;
}

1
投票

在Symfony 4中,您可以使用ParameterBagInterface

use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;

class MessageGenerator
{
    private $params;

    public function __construct(ParameterBagInterface $params)
    {
        $this->params = $params;
    }

    public function someMethod()
    {
        $parameterValue = $this->params->get('parameter_name');
        // ...
    }
}

app/config/services.yaml

parameters:
    locale: 'en'
    dir: '%kernel.project_dir%'

它在控制器和表单类中都适用于我。 More details can be found in the Symfony blog


0
投票

您可以使用:

public function indexAction()
{
   dump( $this->getParameter('api_user'));
}

有关更多信息,我建议您阅读文档:

http://symfony.com/doc/2.8/service_container/parameters.html


-1
投票

您还可以使用:

$container->getParameter('api_user');

访问http://symfony.com/doc/current/service_container/parameters.html

© www.soinside.com 2019 - 2024. All rights reserved.