diff --git a/.env.example b/.env.example index c7c853e..a40ceea 100644 --- a/.env.example +++ b/.env.example @@ -8,3 +8,8 @@ REDIS_HOST=redis REDIS_PASSWORD= REDIS_PORT=6379 REDIS_DB=0 +MYSQL_HOST=mysql +MYSQL_PORT=3306 +MYSQL_USER=mysql +MYSQL_PASSWORD=mysql +MYSQL_DB=db diff --git a/README.md b/README.md index b3f1feb..03ec5ec 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,33 @@ php index.php ``` ### Example +```php +/** + * Set redis options + * @see https://github.com/promphp/prometheus_client_php#usage + */ +RedisStorage::setDefaultOptions([ + 'host' => 'redis', + 'port' => 6379, + 'password' => null, + 'database' => 0, + 'timeout' => 0.1, // in seconds + 'read_timeout' => '10', // in seconds + 'persistent_connections' => false +]); + +/** + * Set mysql options + */ +DB::setDefaultOptions([ + 'host' => 'mysql', + 'port' => '3306', + 'user' => 'mysql', + 'password' => 'mysql', + 'db' => 'db' +]); +``` + ```php // Example gauge from mysql $gauge = $registry->getOrRegisterGauge('rpe', 'testTable', 'Value from mysql'); diff --git a/index.php b/index.php index 14963a6..5df7f70 100644 --- a/index.php +++ b/index.php @@ -39,6 +39,17 @@ 'persistent_connections' => false, ]); +/** + * Set mysql options + */ +DB::setDefaultOptions([ + 'host' => $_ENV['MYSQL_HOST'] ? $_ENV['MYSQL_HOST'] : 'mysql', + 'port' => $_ENV['MYSQL_PORT'] ? $_ENV['MYSQL_PORT'] : '3306', + 'user' => $_ENV['MYSQL_USER'] ? $_ENV['MYSQL_USER'] : 'mysql', + 'password' => $_ENV['MYSQL_PASSWORD'] ? $_ENV['MYSQL_PASSWORD'] : 'mysql', + 'db' => $_ENV['MYSQL_DB'] ? $_ENV['MYSQL_DB'] : 'db', +]); + try { $registry = new CollectorRegistry(new RedisStorage(), false); } catch (\Exception $e) { diff --git a/src/DB.php b/src/DB.php index 7e9f11f..1f150c5 100644 --- a/src/DB.php +++ b/src/DB.php @@ -37,15 +37,42 @@ class DB { */ private Credentials $credentials; + /** + * Credentials options + * @var string[] + */ + private static array $defaultOptions = [ + 'host' => 'mysql', + 'port' => '3306', + 'user' => 'mysql', + 'password' => 'mysql', + 'db' => 'db', + ]; + + /** + * @param mixed[] $options + */ + public static function setDefaultOptions(array $options): void { + self::$defaultOptions = array_merge(self::$defaultOptions, $options); + } + /** * DB constructor + * @param array $options */ - public function __construct() { + public function __construct($options = []) { $loop = ReactAdapter::get(); + self::setDefaultOptions($options); $this->driver = new MysqlDriver($loop); $this->platform = new MySqlPlatform(); - $this->credentials = new Credentials('mysql', '3306', 'mysql', 'mysql', 'db'); + $this->credentials = new Credentials( + self::$defaultOptions['host'], + self::$defaultOptions['port'], + self::$defaultOptions['user'], + self::$defaultOptions['password'], + self::$defaultOptions['db'] + ); $this->conn = SingleConnection::createConnected($this->driver, $this->credentials, $this->platform);