简体   繁体   中英

How do I inject a static method call into a symfony service?

I want to turn this into a service:

        $grpcClient = new MyGrpcClient($_ENV['GRPC_HOST'], [
            'credentials' => \Grpc\ChannelCredentials::createInsecure(),
        ]);

I tried this:

    MyNamespace\MyGrpcClient:
        public: true
        arguments:
            $hostname: '127.0.0.1:44001'
            $opts: ['@Grpc\ChannelCredentials::createInsecure()']

But it doesn't work.

    The service "MyNamespace\MyGrpcClient" has a dependency on a non-existent service "Grpc\ChannelCredentials::createInsecure()".

I suggest using an adapter .


namespace Foo\Bar;

class MyGrpcClientAdapter
{
    private $grpcClient;

    public function __construct()
    {
        $this->grpcClient = new MyGrpcClient($_ENV['GRPC_HOST'], [
            'credentials' => \Grpc\ChannelCredentials::createInsecure(),
        ]);
    }

    public function doSomethingAdaptive(): void
    {
        //...
    }
}

Which can be configured to lazy load into the Symfony container by using:

Foo\Bar\MyGrpcClientAdapter:
    class: 'Foo\Bar\MyGrpcClientAdapter'

You can refactor the adapter to use configurable (host) values like so:

public function __construct(string $host)
{
    $this->grpcClient = new MyGrpcClient($host], [
        'credentials' => \Grpc\ChannelCredentials::createInsecure(),
    ]);
}

Passing (for example) a .env value.

Foo\Bar\MyGrpcClientAdapter:
    class: 'Foo\Bar\MyGrpcClientAdapter'
    arguments:
        - '%env(APP_HOSTNAME)%'

Thanks to ideas from @Jeroen van der Laan, and @Cerad I was able to come up with a solution:

<?php

namespace App\Proto;

use MyNamespace\MyGrpcClient;
use Grpc\ChannelCredentials;

class GrpcClientFactory
{
    public static function create()
    {
        return new MyGrpcClient($_ENV['GRPC_HOST'], [
            'credentials' => ChannelCredentials::createInsecure(),
        ]);
    }
}
// services.yml
    MyNamespace\MyGrpcClient:
        public: true
        factory: ['App\Proto\GrpcClientFactory', 'create']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM