如何在symfony服务中注入静态方法调用?

问题描述 投票:0回答:1

我想把它变成一个服务。

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

我试过这个

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

但是没有用

    The service "MyNamespace\MyGrpcClient" has a dependency on a non-existent service "Grpc\ChannelCredentials::createInsecure()".
php symfony protocol-buffers grpc
1个回答
1
投票

我建议使用 适配器.


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
    {
        //...
    }
}

你可以通过使用.NET Framework 2.0,将其配置为懒加载到Symfony容器中。

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

你可以重构适配器来使用可配置的(主机)值,就像这样。

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

传递(例如)一个 .env 值。

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

0
投票

多亏了@Jeroen van der Laan和@Cerad的想法,我才有了一个解决方案。

<?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']
© www.soinside.com 2019 - 2024. All rights reserved.