【问题标题】:Symfony 3.4 - Auto wire of service not working in methodSymfony 3.4 - 自动服务线无法正常工作
【发布时间】:2019-03-03 11:09:04
【问题描述】:

我对 Symfony 比较陌生,遇到了一些麻烦。 我正在尝试在调用端点时在调用的方法中键入自定义 RequestValidator 类。

使用 Symfony 3.4

但是,我收到以下错误:

控制器“ApiBundle\Endpoints\Healthcheck\v1\Index::check()”要求您为“$request”参数提供一个值。参数可以为空且未提供空值、未提供默认值或因为在此参数之后有一个非可选参数。

这是我的设置:

services.yml 文件

...
        _defaults:
           autowire: true
           autoconfigure: true

...

routing.yml

api.Healthcheck:
path: /healthcheck
controller: ApiBundle\Endpoints\Healthcheck\v1\Index::check
defaults: { _format: json }
methods:
    - GET

然后 - 在 Index 类中,我有以下内容:

<?php

namespace ApiBundle\Endpoints\Healthcheck\v1;

use ApiBundle\Responses\ApiResponse;


class Index extends ApiResponse
{

      public function check(HealthcheckRequest $request) {
        var_dump($request);die;
    }

}

当我执行 debug:autowiring 时,我会在列表中看到我的 HealthcheckRequest。

此外,当我这样做并在 Index 类的构造函数中尝试类型提示时,一切正常。

最后,如果我尝试在 check() 方法中输入 Symfony/HttpFoundation/Request 提示,它会正确实例化它。

总结:

不工作:

  • check(HealthcheckRequest $request)

工作:

  • __construct(HealtcheckRequest $request)
  • 检查(SymfonyRequest $request)

我做错了吗?任何帮助表示赞赏。

【问题讨论】:

  • 您的实际代码中是否有 HealtheckRequest 的 use 语句?
  • ApiResponse 只是一个名称不佳的控制器基类吗?动作注入仅适用于控制器动作。除非这个健康包做了一些非常有趣的事情。
  • HealtcheckRequest 在同一个命名空间中,但我尝试使用和不使用 use 语句,结果相同。
  • ApiResponse 是一个仅包含 jsonResponse() 方法的基类,该方法返回 ApiJsonResponse 类的实例,该类是 Symfony 提供的 JsonResponse 类的“流畅”包装器,允许类似 $this-> Index 类中的 jsonResponse()->addResponseData()->setResponseCode()->getResponse()。它没有扩展 Symfony 的 Controler 类。
  • 你看过这个问题吗? Autowire doesn't seems to be working

标签: php symfony dependency-injection autowired


【解决方案1】:

它是 Symfony 4 中 services.yaml 的一部分,但在 3.3 版中引入,所以这可能会有所帮助:

# controllers are imported separately to make sure services can be injected
# as action arguments even if you don't extend any base controller class

ApiBundle\Endpoints\:
    resource: '../../Endpoints/*'
    tags: ['controller.service_arguments']

【讨论】:

    猜你喜欢
    • 2018-11-02
    • 1970-01-01
    • 2018-08-05
    • 1970-01-01
    • 2016-03-11
    • 1970-01-01
    • 2018-11-21
    • 2015-03-06
    • 1970-01-01
    相关资源
    最近更新 更多