PHP code example of phpdevcommunity / php-dotenv

1. Go to this page and download the library: Download phpdevcommunity/php-dotenv library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

phpdevcommunity / php-dotenv example snippets


    
    evCommunity\DotEnv;

    $envFile = __DIR__ . '/.env';

    // Load environment variables
    (new DotEnv($envFile))->load();

    // Access variables
    var_dump(getenv('APP_ENV')); // string(3) "dev"
    var_dump($_ENV['DEBUG']);    // bool(true)
    

namespace App\Processor;

use PhpDevCommunity\Processor\AbstractProcessor;

class ArrayProcessor extends AbstractProcessor
{
    public function canBeProcessed(): bool
    {
        // Process only if value contains a comma
        return strpos($this->value, ',') !== false;
    }

    public function execute()
    {
        return array_map('trim', explode(',', $this->value));
    }
}

use PhpDevCommunity\DotEnv;
use PhpDevCommunity\Processor\BooleanProcessor;
use PhpDevCommunity\Processor\NullProcessor;
use PhpDevCommunity\Processor\NumberProcessor;
use PhpDevCommunity\Processor\QuotedProcessor;
use App\Processor\ArrayProcessor;

$processors = [
    BooleanProcessor::class,
    NullProcessor::class,
    NumberProcessor::class,
    QuotedProcessor::class,
    ArrayProcessor::class // Your custom processor
];

(new DotEnv(__DIR__ . '/.env', $processors))->load();

    
    evCommunity\DotEnv;

    $envFile = __DIR__ . '/.env';

    // Charger les variables d'environnement
    (new DotEnv($envFile))->load();

    // Accéder aux variables
    var_dump(getenv('APP_ENV')); // string(3) "dev"
    var_dump($_ENV['DEBUG']);    // bool(true)
    

namespace App\Processor;

use PhpDevCommunity\Processor\AbstractProcessor;

class ArrayProcessor extends AbstractProcessor
{
    public function canBeProcessed(): bool
    {
        // Traiter uniquement si la valeur contient une virgule
        return strpos($this->value, ',') !== false;
    }

    public function execute()
    {
        return array_map('trim', explode(',', $this->value));
    }
}

use PhpDevCommunity\DotEnv;
use PhpDevCommunity\Processor\BooleanProcessor;
use PhpDevCommunity\Processor\NullProcessor;
use PhpDevCommunity\Processor\NumberProcessor;
use PhpDevCommunity\Processor\QuotedProcessor;
use App\Processor\ArrayProcessor;

$processors = [
    BooleanProcessor::class,
    NullProcessor::class,
    NumberProcessor::class,
    QuotedProcessor::class,
    ArrayProcessor::class // Votre processeur personnalisé
];

(new DotEnv(__DIR__ . '/.env', $processors))->load();
bash
composer 
bash
composer 
dotenv
    APP_ENV=dev
    DATABASE_URL="mysql:host=localhost;dbname=test"
    DEBUG=true
    CACHE_TTL=3600
    API_KEY=null
    # Ceci est un commentaire