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

Technical Evaluation

Architecture Fit

  • Laravel Synergy: The package’s minimalist design avoids reinventing Laravel’s env() helper but fills gaps in type safety and framework-agnostic consistency. Ideal for:
    • Microservices: Standardizing config access across PHP services (Laravel + non-Laravel).
    • Legacy Code: Replacing ad-hoc getenv() with a maintainable API.
    • Multi-Environment Apps: Enforcing typed defaults (e.g., envBool('FEATURE_FLAG', false)) to prevent runtime errors.
  • Complementarity: Can coexist with Laravel’s config() system by acting as a low-level abstraction for non-cached variables (e.g., runtime overrides, CLI tools).
  • Opportunity Cost: Overkill for projects already using Laravel’s env() + phpdotenv for advanced features (e.g., validation, encryption).

Integration Feasibility

  • Drop-in Replacement: Directly replaces getenv()/$_ENV in non-Laravel contexts (e.g., Artisan commands, queues). For Laravel web layers, it’s best used as a utility layer alongside config().
  • Dependency Risks:
    • None: Zero hard dependencies; MIT license ensures compatibility.
    • Soft Risks: May conflict with existing env() wrappers or custom config loaders.
  • Laravel-Specific Challenges:
    • Caching: Laravel’s config() caches .env values; this package doesn’t, which could lead to performance tradeoffs in high-traffic apps.
    • Service Providers: Requires explicit bootstrapping if used outside Laravel’s container.

Technical Risk

  • Type Safety Illusion:
    • envBool('KEY') may return false for "0", "false", or null, leading to unexpected behavior. Requires explicit validation rules.
    • Mitigation: Add custom parsers or use envString() + manual casting.
  • Adoption Friction:
    • Laravel Devs: May resist switching from config('key') to envString('KEY') due to caching differences.
    • Legacy Code: getenv() calls in frameworks like Symfony or plain PHP may need selective replacement.
  • Testing Complexity:
    • Mocking environment variables in PHPUnit requires custom setup (e.g., overriding $_ENV or using putenv()).
    • Solution: Create a test helper (e.g., setEnvVarsForTest()).

Key Questions

  1. Scope:
    • Will this replace all getenv() usage, or only in specific layers (e.g., CLI tools)?
    • Should it integrate with Laravel’s config caching (e.g., via a service provider)?
  2. Type Handling:
    • Are there custom validation rules needed (e.g., rejecting "off" for booleans)?
    • How will edge cases (e.g., null defaults, empty strings) be standardized?
  3. Performance:
    • Will this be used in high-frequency loops (e.g., real-time processing)? If so, caching may be required.
  4. Secrets Management:
    • How will it integrate with secret managers (e.g., Vault, AWS SSM) that inject env vars at runtime?
  5. Migration Strategy:
    • Should getenv() calls be deprecated first (via linters) before replacement?
    • Will a facade be created to wrap Laravel’s env() for consistency?

Integration Approach

Stack Fit

  • Laravel Web Layer:
    • Use Case: Runtime overrides, CLI tools, or non-cached config (e.g., feature flags).
    • Fit: Complements config() but avoids caching overhead. Example:
      // Instead of:
      if (config('features.new_ui')) { ... }
      
      // Use:
      if (envBool('FEATURE_NEW_UI', false)) { ... }
      
  • Microservices/Non-Laravel:
    • Use Case: Shared libraries, queues, or Symfony components where Laravel’s helpers aren’t available.
    • Fit: Primary solution for consistent env var access.
  • CI/CD:
    • Use Case: Pipeline configurations (e.g., GitHub Actions secrets).
    • Fit: Provides a standardized API for accessing build-time variables.
  • Legacy PHP:
    • Use Case: Modernizing scripts with getenv() anti-patterns.
    • Fit: Drop-in replacement with type safety.

Migration Path

Phase Action Tools/Examples
Audit Identify getenv()/$_ENV usage via static analysis. git grep -r 'getenv|$_ENV' -- '!vendor/'
Pilot (CLI/Jobs) Replace getenv() in Artisan commands, queues, and cron jobs. Before: getenv('QUEUE_DRIVER') After: envString('QUEUE_DRIVER')
Shared Libraries Adopt in framework-agnostic code (e.g., shared kernels, utilities). envInt('MAX_RETRIES', 3)
Laravel Bridge Create a facade to unify env() and the package: ```php
// app/Helpers/EnvHelper.php
function env($key, $default = null) {
    return app()->runningInConsole()
        ? \php_stdlib\env\env($key, $default)
        : config($key, $default);
}
``` |

| Web Layer (Optional)| Replace config() for non-cached variables (e.g., runtime flags). | envBool('MAINTENANCE_MODE') instead of config('maintenance') | | Deprecation | Add PHPStan rules to flag getenv() usage. | Custom rule: NoGetenvUsage |

Compatibility

  • Laravel:
    • Pros: Works alongside config(); no framework modifications.
    • Cons: No native support for cached configuration or .env file scanning.
    • Workaround: Use the package for runtime-only vars and config() for cached ones.
  • Non-Laravel:
    • Pros: Full compatibility with plain PHP, PSR-15, or Symfony.
    • Cons: Requires manual .env loading (e.g., vlucas/phpdotenv).
  • Type Systems:
    • Pros: Integrates with PHP 8.1+ typed properties and IDE autocompletion.
    • Cons: No runtime type enforcement (e.g., envInt() accepts "abc").

Sequencing

  1. CLI/Jobs: Highest ROI—replace getenv() in non-web code first.
  2. Shared Libraries: Ensure consistency across multi-repo projects.
  3. Laravel Web: Use selectively for non-cached vars (e.g., feature toggles).
  4. CI/CD: Standardize variable access in pipelines before runtime code.
  5. Deprecate: Phase out getenv() via linters and IDE warnings.

Operational Impact

Maintenance

  • Pros:
    • Reduced Boilerplate: Eliminates repetitive getenv() calls with defaults.
    • Centralized Logic: Easier to update validation rules (e.g., IP ranges, port numbers).
    • Consistent Naming: Enforces SNAKE_CASE conventions across teams.
  • Cons:
    • New Dependency: Adds a package to composer.json, requiring version updates.
    • API Drift: Future Laravel changes to env() may require package updates.
    • Testing Overhead: Mocking env vars in tests requires custom setup.

Support

  • Debugging:
    • Easier: Typed helpers catch errors early (e.g., envInt() fails on "abc").
    • Harder: Stack traces may obscure original getenv() calls if not wrapped.
  • Onboarding:
    • Quick for PHP Devs: Familiar env* syntax; minimal learning curve.
    • Steep for Laravel Devs: May need to unlearn reliance on config() caching.
  • Documentation:
    • Gap: Lacks Laravel-specific examples (e.g., caching, service providers).
    • Mitigation: Create internal docs with side-by-side comparisons of env() vs. envString().

Scaling

  • Performance:
    • Negligible Overhead: Comparable to getenv(); no significant impact on memory/CPU.
    • Caching: Unlike Laravel’s config(), this package doesn’t cache by default, which is good for runtime flexibility but may require manual caching in high-frequency loops.
  • Distributed Systems:
    • Secrets Management: Works with external secret stores (
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope