AP\Env is a library for managing environment variables with validation and object transformation capabilities.
composer require ap-lib/env
- Retrieve environment variables as objects with validation
- Supports structured JSON environment variables
- Includes validation mechanisms with error handling
- PHP 8.3 or higher
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();
}
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();
}
$debugMode = Env::bool('DEBUG_MODE', false);
if ($debugMode) {
echo "Debug mode is enabled";
}
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();