Symfony4使用外部类库作为服务 [英] Symfony4 use external class library as a service

查看:121
本文介绍了Symfony4使用外部类库作为服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a little external library that expose many classes.

进入我的symfony4项目中,我想从供应商处声明我的类,作为具有autowire和public的服务。
因此,我将我的库包含在composer中,并将这样的psr配置添加到composer.json中:

Into my symfony4 project I would like to declare my class from vendor, as a service with autowire and public. So I have include my library with composer and add psr configuration like this into composer.json:

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

之后,我尝试更改我的services.yaml像这样进入symfony:

After that I have tried to change my services.yaml into symfony like this:

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

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

If I launch tests or run the application returns me this error:

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中声明接口,则可以正常工作:

If I declare into services.yaml the interface this works fine:

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

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

But I have many classes and I don't want to declare each class, how can I fix services.yaml without declare every single service?

谢谢

推荐答案

您需要手工创建服务:
我没有对其进行测试,但是应该看起来像这样

You need to create services by hand: I did not test it but it should look like this

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)
    {

    }
}

更准确地说,您应该有以下类似内容

To be more precise you should have something like

ExternalLibrary\Domain\Model\Repository:
    alias: App\Infrastructure\Domain\Model\MysqlRepository

这篇关于Symfony4使用外部类库作为服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆