Overview

Description

Caldera Settings is an ENV file loader and settings helper.

As with the other Caldera components it has been built to be swappable and modular.

Installation

The easisest way to install it is to use Composer:

composer require vecode/caldera-settings

Requires

  • php: >=8.1
  • ext-mbstring: *

Basic usage

Getting started

Just create a new Settings object and call the load method, passing the path to the directory where the .env file is located:

use Caldera\Settings\Settings;

$settings = new Settings();
$settings->load( dirname(__FILE__) );

The specified path (the root path) can also contain the settings directory, where you can put your configuration files, using the following structure:

-- <root path>
  -- <.env file>
  -- <settings directory>
    -- <app.php>
    -- <database.php>

You can place as many files inside the settings directory as you want, for example here are the contents of the .env file:

DB_HOST=localhost
DB_USER=contosso
DB_PASS=k6Kp0N4jRwT1hFt
DB_NAME=contosso

And inside the /settings directory we have a database.php file with the following contents:

<?php

return [
    'host' => env('DB_HOST'),
    'user' => env('DB_USER'),
    'pass' => env('DB_PASS'),
    'name' => env('DB_NAME'),
];

That way you can do the following:

use Caldera\Settings\Settings;

$settings = new Settings();
$settings->load( dirname(__FILE__) );

$options = [
    'host' => $settings->get('database.host', 'localhost'),
    'user' => $settings->get('database.user'),
    'pass' => $settings->get('database.pass'),
    'name' => $settings->get('database.name'),
];

As you can see, to get the actual values you'll use dot-notation, and the get method can receive a second argument, a default value to use if the specified key is not found.

For more advanced usage you may also specify the name of both the .env file and the settings directory name by passing the corresponding arguments to the load method:

use Caldera\Settings\Settings;

$settings = new Settings();
$settings->load( dirname(__FILE__), 'config', 'testing.env' );