Symfony 4 使用外部类库作为服务

2024-01-21

我有一个小的外部库,公开了许多类。

在我的 symfony4 项目中,我想将我的类从供应商声明为具有自动装配和公共功能的服务。 因此,我已将我的库包含在 Composer 中,并将如下的 psr 配置添加到 Composer.json 中:

"autoload": {
        "psr-4": {
            "App\\": "src/",
            "ExternalLibrary\\": "vendor/external-library/api/src/"
        }
    }

之后我尝试将 services.yaml 更改为 symfony,如下所示:

ExternalLibrary\:
    resource: '../vendor/external-library/api/src/*'
    public: true
    autowire: true

如果我启动测试或运行应用程序,则会返回此错误:

Cannot autowire service "App\Domain\Service\MyService": argument "$repository" of method "__construct()" references interface "ExternalLibrary\Domain\Model\Repository" but no such service exists. You should maybe alias this interface to the existing "App\Infrastructure\Domain\Model\MysqlRepository" service.

如果我在 services.yaml 中声明该接口,则可以正常工作:

ExternalLibrary\Domain\Model\Lotto\Repository:
    class: '../vendor/external-library/api/src/Domain/Model/Repository.php'
    public: true
    autowire: true

但我有很多类,我不想声明每个类,如何在不声明每个服务的情况下修复 services.yaml?

Thanks


您需要手动创建服务: 我没有测试它,但它应该看起来像这样

服务.yaml

Some\Vendor\:
    resource: '../vendor/external-library/api/src/*'
    public: true # should be false

Some\Vendor\FooInterface:
    alias: Some\Vendor\Foo # Interface implementation

Some\Vendor\Bar:
    class: Some\Vendor\Bar
    autowire: true

php

<?php

namespace Some\Vendor;

class Foo implements FooInterface
{

}

class Bar
{
    public function __construct(FooInterface $foo)
    {

    }
}

更准确地说,你应该有类似的东西

ExternalLibrary\Domain\Model\Repository:
    alias: App\Infrastructure\Domain\Model\MysqlRepository
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Symfony 4 使用外部类库作为服务 的相关文章

随机推荐