websitesql/config

A simple configuration management library by Website SQL.

v1.0.0 2025-04-14 23:23 UTC

This package is auto-updated.

Last update: 2025-04-14 23:25:09 UTC


README

A simple, flexible configuration management library for PHP applications. This package provides easy access to configuration files and environment variables.

Features

  • Load and parse environment variables from .env files
  • Access configuration values from PHP files with dot notation
  • Convert environment variable strings to appropriate PHP types
  • Simple API for retrieving configuration values

Installation

composer require websitesql/config

Basic Usage

Setting Up

  1. Create a .env file in your project root:
APP_NAME=MyApplication
APP_ENV=local
APP_DEBUG=true
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=mydatabase
DB_USERNAME=root
DB_PASSWORD=
  1. Create PHP configuration files in a config directory:
// config/app.php
return [
    'name' => env('APP_NAME', 'WebsiteSQL'),
    'env' => env('APP_ENV', 'production'),
    'debug' => env('APP_DEBUG', false),
];

// config/database.php
return [
    'default' => env('DB_CONNECTION', 'mysql'),
    'connections' => [
        'mysql' => [
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
        ],
    ],
];
  1. Initialize the Config class:
use WebsiteSQL\Config\Config;

// Pass your application's base path to the constructor
$config = new Config(__DIR__);

Retrieving Configuration Values

// Get a configuration value with dot notation
$appName = $config->get('app.name'); // Returns the value from config/app.php['name']
$dbHost = $config->get('database.connections.mysql.host'); // Nested arrays are supported

// Specify a default value if the configuration key doesn't exist
$timezone = $config->get('app.timezone', 'UTC');

API Reference

Config Class

__construct(string $basePath)

Initializes the Config class with the base path of your application.

  • $basePath: The absolute path to your application's root directory.

get(string $key, mixed $default = null): mixed

Retrieves a configuration value using dot notation.

  • $key: The configuration key in dot notation (e.g., 'app.name').
  • $default: The default value to return if the key doesn't exist.

env() Function

env(string $key, mixed $default = null): mixed

Retrieves the value of an environment variable from various sources.

  • $key: The name of the environment variable.
  • $default: The default value to return if the environment variable doesn't exist.

Special string values are converted automatically:

  • "true"true (boolean)
  • "false"false (boolean)
  • "null"null
  • "empty""" (empty string)

Directory Structure