When running PHP applications using orchestration systems (like Docker Swarm / Kubernetes) a lot of configuration is done using environment variables.
While PHP comes with getenv()
for reading environmnet variables, a lot of time it proves limited when dealing with secrets (reading values from files) or explicitly casting the values to a certain type.
- PHP 5.3
- Import package namespace
use Nixiware\Config\EnvVar;
- Import environment variables using the static method
get($name, $required, $default, $explicitCastType)
$name
- name of the environmnet variable$required
- sets the variable as required / optional for the execution$default
- default value to return if environment variable is not set$explicitCastType
- explicitly cast the returned value to a type
EnvVar will first look for an environment variable with the suffix _FILE
, and if a file path is specified, it will load the contents of that file.
If a variable is specified as required and no default value is provided, a Nixiware\Config\Exception
will be thrown.
- Reading a variable named
DB_HOST
, set as not required with a default value of127.0.0.1
EnvVar::get('DB_HOST', false, '127.0.0.1');
- Reading a variable named
REST_API_ENABLED
, set as required with no default value, and casted as a boolean.
EnvVar::get('REST_API_ENABLED', true, null, EnvVar::TypeBool);
- Reading a variable from a file, named
DB_PASSWORD
, set as required with no default value.
EnvVar::get('DB_PASSWORD', true);
Path for the file will be specified using the environment variable DB_PASSWORD_FILE
. The variable with the suffix _FILE
is automatically read to allow more flexibility in configuring your application, without requiring to modify the actual configuration files.
Giving the fact that the package is designed to help with Docker / Kubernetes deployments, the unit tests must be ran inside a Docker container.
- Open
docker/
directory and runbash deployment-start.sh
to start the container - Connect to container (similar to SSH) by running
bash container-ssh.sh
- Run the install script
bash install.sh
(inside the container) - Run the tests script
bash run-tests.sh
(inside the container)
For cleanup simply run bash deployment-stop.sh
after exiting the container.
Config is available under the MIT license. See the LICENSE file for more info.