Symfony3.3:使用标量参数自动装配控制器

2024-03-28

我的控制器包含具有标量依赖性的操作$bugReportRecipient.

class DefaultController
{
    public function bugReportAction(SwiftTwigMailer $swiftTwigMailer, string $bugReportRecipient, Request $request)
    {
        // more code
    }
}

我的服务定义如下:

AppBundle\Controller\DefaultController:
    autowire: true
    tags: ['controller.service_arguments']

如果我运行该操作,则会显示此错误:

Controller "AppBundle\Controller\DefaultController::bugReportAction()" requires that you provide a value for the "$bugReportRecipient" argument. Either the argument is nullable and no null value has been provided, no default value has been provided or because there is a non optional argument after this one.

我怎样才能注入这个论点?到目前为止,我还没有在 symfony 文档中找到任何有用的信息。

[EDIT]:

论据$bugReportRecipient是在我的中定义的参数parameters.yml.


操作的值来自与之前相同的位置 - 您可以在函数定义中设置默认值,或者至少有一个由路由给出的值,可以这样设置:

* @Route("/bug-report/{bugReportRecipient}", name="bugreport", 
*        defaults={"bugReportRecipient" = "username"})

The SwiftTwigMailer被注入是因为controller.service_arguments标签的方式与Request以前有过。

注意 - 您仍然可以在 @Route 中为未出现在 {URL} 部分中的变量设置变量的默认值 - 但必须在某处设置它。

我已经使用这种技术根据正在使用的特定路线为变量设置不同的值。

 * @Route("/",         name="homepage_menus", 
 *        defaults={"hasMenus"=true, "partnerLinks"=false})
 * @Route("/partners", name="homepage_partner_footer", 
 *        defaults={"hasMenus"=false,"partnerLinks"=true})

这些变量(它们也已在函数定义中设置了默认值)都不能出现在 URL 中,而是根据所使用的路由进行设置。


如果 $bugReportRecipient 是一个参数,则可以在服务定义中设置它,如下所示:

arguments:
    $bugReportRecipient: "%kernel.environment%" # or whatever

似乎没有办法在操作级别上设置它,因此您必须使控制器成为更正式的服务,并至少在类级别上设置此参数。

您也许还可以使用表达式语言来执行此操作。

services:
    AppBundle\Mailer:
        arguments: ["@=container.hasParameter('some_param') ? parameter('some_param') : 'default_value'"]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Symfony3.3:使用标量参数自动装配控制器 的相关文章

随机推荐