[英]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:可以将其配置为延迟加载到 Symfony 容器中,方法是:
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.传递(例如)一个
.env
值。
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:感谢@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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.