ap-lib/env

dev-main 2025-03-11 03:47 UTC

This package is auto-updated.

Last update: 2025-03-11 03:50:00 UTC


README

MIT License

AP\Env is a library for managing environment variables with validation and object transformation capabilities.

Installation

composer require ap-lib/env

Features

  • Retrieve environment variables as objects with validation
  • Supports structured JSON environment variables
  • Includes validation mechanisms with error handling

Requirements

  • PHP 8.3 or higher

Getting started

Base use case

use AP\Env\Env;
use AP\Scheme\ToObject;
use AP\Scheme\Validation;

class Config implements ToObject, Validation {
    // Implementation of ToObject and Validation
}

try {
    $config = Env::obj('CONFIG_VAR', Config::class);
    // Use $config as needed
} catch (Throwable $e) {
    echo "Error loading configuration: " . $e->getMessage();
}

String Validation Example

use AP\Validator\ValidatorInterface;

class NotEmptyValidator implements ValidatorInterface {
    public function validate(mixed $value): ?Errors {
        return empty($value) ? new Errors([new Error(["value"], "Value cannot be empty")]) : null;
    }
}

try {
    $value = Env::str('MY_ENV_VAR', [new NotEmptyValidator()]);
} catch (Throwable $e) {
    echo "Error: " . $e->getMessage();
}

Boolean Parsing Example

$debugMode = Env::bool('DEBUG_MODE', false);
if ($debugMode) {
    echo "Debug mode is enabled";
}

Lazy Loading with MyEnv

You can create a custom environment loader using a static class that extends Env.

use AP\Env\Env;
use AP\Database\Mysql;

class MyEnv extends Env
{
    public static function DB_AUTH(): Mysql
    {
        return self::obj(__FUNCTION__, Mysql::class);
    }

    public static function PROD(): bool
    {
        return self::bool(__FUNCTION__, false);
    }
}

$dbAuth = MyEnv::DB_AUTH();
$isProd = MyEnv::PROD();