PHP code example of horat1us / environment-config

1. Go to this page and download the library: Download horat1us/environment-config 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/ */

    

horat1us / environment-config example snippets




namespace App;

use Horat1us\Environment;

class Config extends Environment\Config {
    public function getTimeout(): int
    {
        return $this->getEnv($key = 'APP_TIMEOUT', $default = 10);
    }
    
    public function getSlow(): string
    {
        // default can be instance of \Closure or callable array, like [$this, 'calculate']
        return $this->getEnv($key = 'APP_KEY', $default = function(): string {
            return 'some-string'; // slow operation, may be fetching from DB 
        });
    }
    
    public function getNullValue(): ?string
    {
        /**
          * if you want to return null instead of throwing exceptio
          * if no environment variable found
          */
        return $this->getEnv('KEY', [$this, 'null']);  
    }
    
    public function getName(): string {
        return $this->getEnv($key = 'APP_NAME');
    }
}



use App;

$config = new App\Config("PREFIX_");
$config->getTimeout(); // 10

putenv("PREFIX_APP_TIMEOUT=5");
$config->getTimeout(); // 5

$config->getSlow(); // some-string

// MissingEnvironmentException will be thrown because no default value provided
$config->getName(); 



use Horat1us\Environment;

class Config {
    use Environment\MagicTrait {
        getEnvironment as public getHost;
    }
    
    protected function getEnvironmentKeyPrefix(): string {
        return 'TEST_';
    }
}

$config = new Config;
$config->getHost(); // TEST_HOST environment key will be used to get value