Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Env Laravel Package

php-standard-library/env

Tiny PHP utility for reading environment variables with sensible defaults and type casting. Helps centralize access to config via env(), supports required keys, fallback values, and safe handling when variables are missing or empty.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require php-standard-library/env
    

    Add to composer.json under autoload if not auto-discovered:

    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "PhpStandardLibrary\\Env\\": "vendor/php-standard-library/env/src/"
        }
    }
    

    Run composer dump-autoload.

  2. First Use Case: Fetch a string env var with a fallback:

    use PhpStandardLibrary\Env\Env;
    
    $appName = Env::get('APP_NAME', 'MyApp');
    
  3. Where to Look First:

    • Source Code (if available) for API reference.
    • Focus on Env class methods: get(), getBool(), getInt(), getArray(), etc.
    • Check tests/ for usage examples (if included).

Implementation Patterns

Core Workflows

  1. Centralized Configuration Access: Replace scattered getenv() calls with a single entry point:

    // Before
    $debug = getenv('APP_DEBUG') === 'true';
    
    // After
    $debug = Env::getBool('APP_DEBUG', false);
    
  2. Type-Safe Retrieval: Use typed methods to avoid manual casting:

    $port = Env::getInt('APP_PORT', 8000);
    $enabled = Env::getBool('FEATURE_X', true);
    $tags = Env::getArray('ALLOWED_TAGS', []);
    
  3. Framework Integration:

    • Laravel: Replace config('app.name') with Env::get('APP_NAME') for runtime overrides.
    • Symfony: Use in ParameterBag or Dotenv alternatives for dynamic configs.
    • Plain PHP: Load env vars early in index.php:
      require __DIR__.'/vendor/autoload.php';
      $env = new PhpStandardLibrary\Env\Env();
      
  4. Validation Layer: Combine with validation libraries (e.g., Respect/Validation) for runtime checks:

    $timeout = Env::getInt('HTTP_TIMEOUT');
    $validator = new Validator();
    $validator->validate($timeout, Validation::numeric()->positive());
    
  5. Environment-Specific Bootstrapping: Load different configs per environment:

    $env = Env::get('APP_ENV', 'local');
    $config = require __DIR__."/config/{$env}.php";
    

Integration Tips

  • Dotenv Compatibility: Use with vlucas/phpdotenv for .env files:
    $dotenv = new Dotenv\Dotenv(__DIR__);
    $dotenv->load();
    $value = Env::get('DB_HOST');
    
  • Caching: Cache env values in a singleton or static class if performance is critical.
  • Testing: Mock Env in unit tests:
    $env = $this->getMockBuilder(PhpStandardLibrary\Env\Env::class)
        ->disableOriginalConstructor()
        ->onlyMethods(['get'])
        ->getMock();
    $env->method('get')->with('API_KEY')->willReturn('test_key');
    

Gotchas and Tips

Pitfalls

  1. Case Sensitivity: Env vars are case-sensitive by default (e.g., APP_DEBUGapp_debug). Use Env::get('APP_DEBUG', false) consistently.

  2. Empty Values: Env::get() returns null for missing/empty vars. Always provide defaults:

    // Bad: Assumes 'APP_NAME' exists
    $name = Env::get('APP_NAME');
    
    // Good: Explicit fallback
    $name = Env::get('APP_NAME', 'default');
    
  3. Type Coercion Quirks:

    • getBool() treats "1", "true", "on" as true; "0", "false", "off" as false. Empty strings return false.
    • getInt() returns 0 for empty strings (not null). Use Env::get('VAR') === null to check for missing vars.
  4. Overriding Defaults: Avoid hardcoding defaults in Env::get() calls. Centralize them in a config file or service:

    // config/env.php
    return [
        'APP_NAME' => 'MyApp',
        'DEBUG' => false,
    ];
    
  5. Performance: The package is lightweight, but avoid calling Env::get() in tight loops. Cache results if needed.

Debugging

  • Missing Vars: Use Env::has('VAR') to check existence before retrieval:
    if (Env::has('DB_PASSWORD')) {
        $password = Env::get('DB_PASSWORD');
    }
    
  • Type Mismatches: Log raw values to debug:
    $raw = getenv('VAR');
    error_log("Raw value for VAR: " . json_encode($raw));
    
  • CI/CD Issues: Ensure env vars are set in your deployment pipeline (e.g., GitHub Actions, Docker):
    # GitHub Actions example
    env:
        APP_ENV: production
        DB_HOST: ${{ secrets.DB_HOST }}
    

Extension Points

  1. Custom Types: Extend the Env class to add methods for complex types (e.g., getJson()):

    class ExtendedEnv extends PhpStandardLibrary\Env\Env {
        public static function getJson(string $key, mixed $default = null): mixed {
            $value = self::get($key, $default);
            return json_decode($value, true);
        }
    }
    
  2. Custom Sources: Override the data source (e.g., read from a database or API):

    class CustomEnv extends PhpStandardLibrary\Env\Env {
        protected static function getSource(): array {
            return $this->fetchFromDatabase();
        }
    }
    
  3. Validation Hooks: Add pre-get validation:

    Env::extend('validated', function ($key, $default = null) {
        $value = Env::get($key, $default);
        if ($key === 'API_KEY' && empty($value)) {
            throw new RuntimeException('API_KEY is required');
        }
        return $value;
    });
    
  4. Framework-Specific Adapters: Create adapters for Laravel/Symfony to integrate with their config systems:

    class LaravelEnvAdapter {
        public static function get(string $key, mixed $default = null) {
            return config($key, Env::get($key, $default));
        }
    }
    

Configuration Quirks

  • Default Values in Tests: Override env vars in tests without modifying .env:
    putenv('APP_ENV=testing');
    $this->assertEquals('testing', Env::get('APP_ENV'));
    
  • Order of Precedence: The package respects the order of getenv(), $_ENV, and $_SERVER. Use ini_set('variables_order', 'EGPCS') to control this if needed.
  • Windows Compatibility: On Windows, env vars are case-insensitive. Normalize keys if cross-platform support is needed:
    $key = strtoupper('app_name');
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport