Symfony yaml配置:执行纯php代码



Symfony框架4.4

这是我的config/services.yaml文件:

parameters:
...
app.dogstatsd.config:
host: 'some_host_name.domain.com'
global_tags:
node: 'hostname'
env: '%env(APP_ENV)%'
services:
...
DataDogDogStatsd:
arguments: ['%app.dogstatsd.config%']

我需要node等于PHP gethostname((函数的结果。

在服务器端::

$ hostname
homestead

那么,如何从yaml配置中获取主机名值呢?

我找到了解决方案:

env(HOSTNAME): '../config/.runtime-evaluated.php'
app.dogstatsd.config:
host: 'some_host_name.domain.com'
global_tags:
node: '%env(require:HOSTNAME)%'
env: '%env(APP_ENV)%'

其中

$ cat config/.runtime-evaluated.php'
<?php
declare(strict_types=1);
return gethostname();

我觉得它很难看。。。有人有其他解决方案吗?

编辑:您在hingsight上所做的实际上很好。我想仔细想想,这完全没问题。无论如何,我都会在下面留下我的评论

我不喜欢你试图将完整的配置注入到服务中。既然你说它是可变的,为什么还要麻烦呢。。但为了论证起见,让我们假设你必须……在这一点上,你试图做的事情可能是有意义的,创建一个DependencyInjection Extension,它允许你扩展另一个bundle配置选项的值。

也许可以看看这里:https://symfony.com/doc/4.1/bundles/prepend_extension.html

例如,您可以创建一个文件。。选择您自己的命名和首选捆绑包将其添加到…

// src/AppDDoggerBundle/DI/DDWhateverYouWantToCallMeExtension.php

public function prepend(ContainerBundle $container){
// Get existing DD Bundle Config.. 
// (I don't know what the Bundle Alias is called)
$container->loadFromExtension('ddstat', [
'key' => 'value'
]);

}

使用Helper Service来访问DDStatt不是更有意义吗?

例如。。。

<?php
/**
* Created by Helpful Stackoverflow User.
* User: layke
* Date: 02/12/20
* Time: 22:17.
*/
namespace AppDataDogBundleService;
use DataDogDogStatsd;
/**
* Class DDStatter.
*
* @method timing(string $stat, float $time, float $sampleRate, array | string $tags)
* @method microtiming(string $stat, float $time, float $sampleRate, array | string $tags)
* @method gauge(string $stat, float $value, float $sampleRate, array | string $tags)
* @method histogram(string $stat, float $value, float $sampleRate, array | string $tags)
* @method distribution(string $stat, float $value, float $sampleRate, array | string $tags)
* @method set(string $stat, float $value, float $sampleRate, array | string $tags)
* @method increment(string | array $stat, float $sampleRate, array | string $tags, float $value)
* @method decrement(string | array $stat, float $sampleRate, array | string $tags, float $value)
* @method updateStats(string | array $stat, int $delta, float $sampleRate, array | string $tags)
* @method serialize_tags(array | string $tags)
* @method normalize_tags(mixed $tags)
* @method send(array $data, float $sampleRate, array | string $tags)
*/
class DDStatter
{
private $statd;
/**
* DDStatter constructor.
*/
public function __construct(?string $dataDogApiKey, ?string $dataDogAppKey)
{
$this->statd = new DogStatsd([
'api_key' => $dataDogApiKey,
'app_key' => $dataDogAppKey,
]);
}
public function __call($method, $args)
{
return call_user_func_array([$this->statd, $method], $args);
}
}

最新更新