我是symfony的初学者。当我在symphony中调用get API时,显示如下错误。
RuntimeException
HTTP 500 Internal Server Error
Could not resolve argument $salesteamRepository of "AppControllerSalesController::index()", maybe you forgot to register the controller as a service or missed tagging it with the "controller.service_arguments"?
发生这种情况是因为您当前的类没有充当服务,并且您在类中使用的所有类都没有由symfony自动注入。
如果你想为你创建的所有类自动注入依赖项,你可以将你的类扩展到AbstractController
,比如这个
class MyPet extends AbstractController{}
官方symfony文档中已经提到了这一点。
在Symfony中,控制器不需要注册为服务。但是,如果您使用默认的services.yaml配置控制器扩展了AbstractController类,它们是自动注册为服务。这意味着您可以使用像任何其他正常服务一样进行依赖性注入。
这取决于您的symfony版本。在版本6(可能还有5.4(中,除了autowire:true和autoconfig:true之外,您不需要任何额外的配置。
在旧版本中,您必须告诉框架将您的控制器视为具有自动布线方法的控制器:
# controllers are imported separately to make sure services can be injected
# as action arguments even if you don't extend any base controller class
AppController:
resource: '../src/Controller'
tags: ['controller.service_arguments']
https://symfony.com/doc/current/controller/service.html
由于Symfony 5.3,您可以用PHP属性标记控制器。
#[AsController]
final class HomepageController
{
}
对于其他遇到类似问题的人。如果控制器函数中有一个不存在的变量,也会抛出此错误描述。
例如,我遵循了Cauldron Overflow的SymfonyCasts教程,但更改了URL中变量的名称:
/**
* @Route("/comments/{comment_id}/vote/{direction}")
*/
public function comment_vote(string $id, string $direction): JsonResponse
{
[...]
}
如您所见,url使用{comment_id}
和{direction}
,但函数使用$id
和$direction
。这意味着您必须将string $id
更改为string $comment_id
才能使其工作。
/**
* @Route("/comments/{comment_id}/vote/{direction}")
*/
public function comment_vote(string $comment_id, string $direction): JsonResponse
{
[...]
}