【问题标题】:Passing constructor arguments in routing yml file in Symfony在 Symfony 的路由 yml 文件中传递构造函数参数
【发布时间】:2015-11-26 10:27:29
【问题描述】:

我在尝试调用 Symfony2 项目中的路由时遇到了一些问题,因为我指向的控制器需要参数(即用户名和密码)才能实例化。

情况如下:

我正在将 Kashflow 集成到我的项目中,我需要做的一件事是能够将发票付款从我的 CRM 发送到 Kashflow 帐户。单击“推送付款”按钮时,它会运行一个 ajax 调用,将所需数据发送到我的 Kashflow 控制器中名为 prepareInvoicePayment() 的方法,并且出于测试目的,只需返回请求,以便我可以查看返回的内容。

我的 ajax:

$('.push-kashflow-payment').on('click', function(e) {
        var answer = confirm('Are you sure?');
        var invoiceID = $(this).attr('id').split("_")[0];
        var accountID = $(this).attr('id').split("_")[1];
        var method = 2;
        var amount = $(this).parent().parent().find('.amount').html();

        if (answer) {
            $.post('/kashflow-push-payment', { invoiceID: invoiceID, method: method, accountID: accountID, amount: amount  }
            ).done( function(response) {
                console.log(response);
            });
        }

        e.preventDefault();

        return false;
    });

问题:

我的路由文件有以下条目:

app_push_kashflow_payment:
    path: /kashflow-push-payment
    defaults: { _controller: AppBundle:Kashflow:prepareInvoicePayment }

但是 Kashflow 类需要将用户名和密码传递给构造函数:

function __construct($user, $pass)
    {
        // Set the username and password
        $this->username = $user;
        $this->password = $pass;

        // Hide some simple XML errors we dont want to see
        libxml_use_internal_errors(true);
    }

当 ajax 请求发送到控制器时,我得到以下错误返回:

警告:缺少参数 1 AppBundle\Controller\KashflowController::__construct()

所以,我的问题是,如何在我的路由文件中传递这些值?这甚至是这样做的方法吗?如果可能的话,我宁愿在我的 parameters.yml 文件中设置我的用户名和密码,然后引用它 - 但无论哪种方式,我都需要能够传递这些参数才能使调用正常工作。

任何帮助表示赞赏,谢谢!

【问题讨论】:

  • 使用依赖注入和服务

标签: php ajax symfony yaml


【解决方案1】:

您需要将控制器定义为服务:How to Define Controllers as Services 并在服务定义配置中传递所有参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-27
    • 2017-07-26
    • 2016-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 2015-01-13
    相关资源
    最近更新 更多