Symfony3.3:使用标量参数自动装入控制器
我的控制器包含一个具有标量依赖项的操作$bugReportRecipient
。Symfony3.3:使用标量参数自动装入控制器
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文档中找到任何有用的信息。
[编辑]:
的参数$bugReportRecipient
是其在我的parameters.yml
定义的参数。
该操作的值之前,来自同一个地方 - 你要么设置在函数定义的默认值,或至少具有由途径给予一个值,该值可能设置像这样:
* @Route("/bug-report/{bugReportRecipient}", name="bugreport",
* defaults={"bugReportRecipient" = "username"})
由于controller.service_arguments
标记与Request
之前一样,因此注入了SwiftTwigMailer
标记。
注 - 您仍然可以在@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'"]
'bugReportRecipient'参数来自服务容器,所以它与我的路由定义无关 –
公共职能bugReportAction(SwiftTwigMailer $ swiftTwigMailer,$ bugReportRecipient,请求$要求)只是没有串 –
没有,得到了同样的错误。 –
为什么使用$ bugReportRecipient? –