1. Go to this page and download the library: Download crell/envmapper 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/ */
crell / envmapper example snippets
// Define the class.
class DbSettings
{
public function __construct(
// Loads the DB_USER env var.
public readonly string $dbUser,
// Loads the DB_PASS env var.
public readonly string $dbPass,
// Loads the DB_HOST env var.
public readonly string $dbHost,
// Loads the DB_PORT env var.
public readonly int $dbPort,
// Loads the DB_NAME env var.
public readonly string $dbName,
) {}
}
$mapper = new Crell\EnvMapper\EnvMapper();
$db = $mapper->map(DbSettings::class);
class MissingStuff
{
public function __construct(
public readonly string $notSet,
) {}
}
// This will throw a MissingEnvValue exception unless there is a NOT_SET env var defined.
$mapper->map(MissingStuff::class,
namespace App\Providers;
use App\Environment;
use Crell\EnvMapper\EnvMapper;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\ServiceProvider;
class EnvMapperServiceProvider extends ServiceProvider
{
// The EnvMapper has no constructor arguments, so registering it is simple.
public $singletons = [
EnvMapper::class => EnvMapper::class,
];
public function register(): void
{
// When the Environment class is requested, it will be loaded lazily out of the env vars by the mapper.
// Because it's a singleton, the object will be automatically cached.
$this->app->singleton(Environment::class, fn(Application $app) => $app[EnvMapper::class]->map(Environment::class));
}
}
class AService
{
public function __construct(private readonly AwsSettings $settings) {}
// ...
}
class AServiceTest extends TestCase
{
public function testSomething(): void
$awsSettings = new AwsSettings(awsKey: 'fake', awsSecret: 'fake');
$s = new Something($awsSettings);
// ...
}
}
class DbSettings
{
public function __construct(
public readonly string $dbUser,
public readonly string $dbPass,
public readonly string $dbHost,
public readonly int $dbPort,
public readonly string $dbName,
) {}
}
class AwsSettings
{
public function __construct(
public readonly string $awsKey,
public readonly string $awsSecret,
) {}
}
// Laravel version.
class EnvMapperServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->singleton(DbSettings::class, fn(Application $app) => $app[EnvMapper::class]->map(DbSettings::class));
$this->app->singleton(AwsSettings::class, fn(Application $app) => $app[EnvMapper::class]->map(AwsSettings::class));
}
}
$serde = new SerdeCommon();
$env = $serde->deserialize($_ENV, from: 'array', to: Environment::class);
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.