Symfony4 使用外部类库作为服务

Ale*_*eri 8 php dependency-injection symfony

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

在我的 symfony4 项目中,我想将我的类从供应商声明为具有自动装配和公共的服务。所以我已经将我的库包含在 composer 中,并将这样的 psr 配置添加到 composer.json 中:

"autoload": {
        "psr-4": {
            "App\\": "src/",
            "ExternalLibrary\\": "vendor/external-library/api/src/"
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

ExternalLibrary\:
    resource: '../vendor/external-library/api/src/*'
    public: true
    autowire: true
Run Code Online (Sandbox Code Playgroud)

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

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.
Run Code Online (Sandbox Code Playgroud)

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

ExternalLibrary\Domain\Model\Lotto\Repository:
    class: '../vendor/external-library/api/src/Domain/Model/Repository.php'
    public: true
    autowire: true
Run Code Online (Sandbox Code Playgroud)

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

谢谢

Fab*_*pet 5

您需要手动创建服务:我没有对其进行测试,但它应该是这样的

服务.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
Run Code Online (Sandbox Code Playgroud)

php

<?php

namespace Some\Vendor;

class Foo implements FooInterface
{

}

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

    }
}
Run Code Online (Sandbox Code Playgroud)

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

ExternalLibrary\Domain\Model\Repository:
    alias: App\Infrastructure\Domain\Model\MysqlRepository
Run Code Online (Sandbox Code Playgroud)


MUS*_*SSI 5

我们以Dompdf为例:

当您尝试在操作控制器或服务方法中添加类型提示 Dompdf 时,会出现错误,提示无法自动装配,因为Dompdf外部 PHP 库

因此,为了解决这个问题,我们将通过添加这个简短的配置来对 services.yaml 文件进行一些更改

Dompdf\: #Add the global namespace
   resource: '../vendor/dompdf/dompdf/src/*' #Where can we find your external lib ?
   autowire: true  #Turn autowire to true
Run Code Online (Sandbox Code Playgroud)

将上面的示例应用于所有外部 PHP 库:)

就这样 !