我有一个暴露许多类的外部库。
进入我的symfony4项目,我想从供应商声明我的类,作为autowire和public的服务。所以我将我的库包含在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而不声明每个服务?
谢谢
你需要手工创建服务:我没有测试它,但它应该是这样的
services.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
我们以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
将以上示例应用于所有外部PHP库:)
就这样 !