【问题标题】:symfony: autowiring an interfacesymfony:自动装配接口
【发布时间】:2023-03-16 14:50:01
【问题描述】:

我需要做什么才能完成这项工作?

interface BaseServiceInterface {
   public function getRecords();
} 

class BaseService implements BaseServiceInterface{
    public function getRecords(){
        return "bla";
    }
}


class SomeOtherService{

    private $baseService;

    public function __construct(BaseServiceInterface $baseService){
         $this->baseService = $baseService;
    }
}

我的 service.yml 看起来像这样:

base_service:
    class: AppBundle\Service\BaseService
    autowire: true

当我尝试运行它时,我得到:

无法为 AppBundle\Service\SomeOtherService 自动装配参数 1,因为类型提示的类不存在(类 BaseServiceInterface 不存在)。

【问题讨论】:

  • 您是否在同一个service.yml 文件中注册了SomeOtherService?这些类的所有命名空间都正确吗?
  • @Federkun 是的,当我从构造函数中删除“接口”时=意味着我直接注入了它工作的实现。当我尝试注入接口时,它会返回上面提到的错误。
  • 您可以尝试将autowiring_types: BaseServiceInterface 添加到您的base_service 吗?
  • 你确定SomeOtherService文件中的BaseServiceInterface类的命名空间是正确的吗?
  • 是的。它以某种方式被缓存。我删除了所有缓存的文件,它开始工作。您可以在下面发布您的第二个答案。所以我可以将其标记为“已解决”?谢谢!

标签: php symfony autowired


【解决方案1】:

autowire 不能直接与接口一起使用。 您需要创建服务别名才能使其正常工作。

services:
    AppBundle\Service\BaseServiceInterface: '@AppBundle\Service\BaseService'

参考:https://symfony.com/doc/current/service_container/autowiring.html#working-with-interfaces

【讨论】:

    猜你喜欢
    • 2015-07-17
    • 2011-01-24
    • 2018-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-02
    • 1970-01-01
    • 2017-01-11
    相关资源
    最近更新 更多