Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony4 use external class library as a service

I have a little external library that expose many classes.

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/"
        }
    }

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.

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

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?

Thanks

like image 862
Alessandro Minoccheri Avatar asked Sep 04 '18 10:09

Alessandro Minoccheri


1 Answers

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
like image 183
Fabien Papet Avatar answered Oct 12 '22 18:10

Fabien Papet