diff --git a/docker-compose.yml b/docker-compose.yml index 94129fb..43d2f2f 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -8,6 +8,12 @@ services: - action: sync path: ./www target: /var/www/html + environment: + DATABASE_host: db + DATABASE_port: 5432 + DATABASE_dbname: db + DATABASE_user: user + DATABASE_password: password depends_on: - db volumes: diff --git a/www/dynamic_web_app/Database.php b/www/dynamic_web_app/Database.php index 034b107..08f6bc5 100644 --- a/www/dynamic_web_app/Database.php +++ b/www/dynamic_web_app/Database.php @@ -5,22 +5,24 @@ class Database private $pdo; - function __construct() + function __construct(array $config) { // Connect to Database - $dsn = "pgsql:host=db;port=5432;dbname=db;user=user;password=password"; - $this->pdo = new PDO($dsn); + $dsn = "pgsql:" . http_build_query($config, '', ';'); + $this->pdo = new PDO($dsn, options: [ + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC + ]); } function fetchAll(string $query): array { - return $this->statement($query)->fetchAll(PDO::FETCH_ASSOC); + return $this->statement($query)->fetchAll(); } function fetch(string $query) { - return $this->statement($query)->fetch(PDO::FETCH_ASSOC); + return $this->statement($query)->fetch(); } function statement(string $query) diff --git a/www/dynamic_web_app/config.php b/www/dynamic_web_app/config.php new file mode 100644 index 0000000..41cb38d --- /dev/null +++ b/www/dynamic_web_app/config.php @@ -0,0 +1,24 @@ + + [ + 'host' => 'localhost', + 'port' => 5432, + 'dbname' => '', + 'user' => '', + 'password' => '' + + ] +]; + +foreach (array_keys($default_config) as $key) { + foreach (array_keys($default_config[$key]) as $subkey) { + $keyname = "{$key}_{$subkey}"; + if (array_key_exists($keyname, $_ENV)) { + $default_config[$key][$subkey] = $_ENV[$keyname]; + } + } +} + +return $default_config; \ No newline at end of file diff --git a/www/dynamic_web_app/index.php b/www/dynamic_web_app/index.php index 100de91..96f8f06 100644 --- a/www/dynamic_web_app/index.php +++ b/www/dynamic_web_app/index.php @@ -2,8 +2,9 @@ require "functions.php"; require "Database.php"; -$db = new Database(); +$config = require "config.php"; +$db = new Database($config["DATABASE"]); require "router.php"; \ No newline at end of file