Symfony3.3:使用标量参数自动连接控制器
my controller包含一个具有标量依赖项的操作Symfony3.3:使用标量参数自动连接控制器,symfony,Symfony,my controller包含一个具有标量依赖项的操作$bugReportRecipient class DefaultController { public function bugReportAction(SwiftTwigMailer $swiftTwigMailer, string $bugReportRecipient, Request $request) { // more code } } 我的服务定义如下所示: AppBundle\Con
$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()”要求您为“$bugReportRecipient”参数提供一个值。该参数可为null且未提供null值,未提供默认值,或者因为此参数后面有一个非可选参数。
我怎样才能插入这个论点?到目前为止,我还没有在symfony文档中找到任何有用的东西
[编辑]:
参数
$bugReportRecipient
是myparameters.yml
中定义的参数。操作的值来自与以前相同的位置-您可以在函数定义中设置默认值,或者至少有路由给定的值,可以这样设置:
* @Route("/bug-report/{bugReportRecipient}", name="bugreport",
* defaults={"bugReportRecipient" = "username"})
arguments:
$bugReportRecipient: "%kernel.environment%" # or whatever
SwiftTwigMailer
被注入是因为controller.service\u 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是一个参数,则可以在服务定义中进行如下设置:
* @Route("/bug-report/{bugReportRecipient}", name="bugreport",
* defaults={"bugReportRecipient" = "username"})
arguments:
$bugReportRecipient: "%kernel.environment%" # or whatever
似乎没有办法在操作级别上设置它,因此您必须使控制器成为更正式的服务,并至少在类级别上设置此参数
您也可以使用表达式语言来实现这一点
services:
AppBundle\Mailer:
arguments: ["@=container.hasParameter('some_param') ? parameter('some_param') : 'default_value'"]
没有stringno的公共函数bugReportAction(SwiftTwigMailer$SwiftTwigMailer,$bugReportRecipient,Request$Request)会出现同样的错误。为什么要使用$bugReportRecipient?From:“如果您有一个参数不是对象,它就不能自动连接。”它接着解释了如何仅手动配置一个参数,但示例是针对构造函数的。不确定是否可以为操作方法执行此操作。好奇地想知道。我想真正的黑客是创建一个简单的bug report recipient对象。这可能也有帮助:看起来您可以显式指定特定操作的参数。
bugReportRecipient
参数来自服务容器,因此它与我的路由定义无关