-
-
Couldn't load subscription status.
- Fork 146
Create Runtime Code #160
-
I would like to experiment with using this to create a Config class at runtime based on a .env file for example.
I don't know enough about autoloaders and composer to make much progress, so I'm wondering if anyone has ideas?
Here's what I've got so far:
<?php declare(strict_types=1); namespace Demo; use Nette\PhpGenerator\PhpNamespace; require_once __DIR__ . '/../vendor/autoload.php'; function autoloadConfigClass() { $namespace = new PhpNamespace('Demo'); $configClass = $namespace->addClass('Config'); $constructor = $configClass->addMethod('__construct'); $env = array_keys(array_change_key_case( parse_ini_file(__DIR__ . '/../.env.example'), CASE_LOWER )); foreach ($env as $key) { $constructor->addPromotedParameter($key)->setType('string')->setReadOnly(); } eval((string) $namespace); spl_autoload_unregister('Demo\autoloadConfigClass'); } spl_autoload_register('Demo\autoloadConfigClass');
I'm trying to make it so that when composer tries to autoload the Config class, it loads this file which in turn loads this autoloader, loads the class, then unloads the autoloader.
Is this even possible?
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 2 comments 1 reply
-
I was testing this with:
<?php declare(strict_types=1); namespace Demo; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\TestCase; #[CoversClass(Config::class)] class ConfigTest extends TestCase { public function testThatConfigClassIsLoadedFromEnvArray(): void { $env = array_change_key_case( parse_ini_file(__DIR__ . '/../.env.example'), CASE_LOWER ); $subject = new Config(...$env); $this->assertSame(1025, $subject->smtp_port); } }
for example.
Beta Was this translation helpful? Give feedback.
All reactions
-
Hello!
How can such a class be useful at all? Why would you want to create such a class dynamically?
Beta Was this translation helpful? Give feedback.
All reactions
-
Personal belief that you shouldn't use functions like getenv inside OOP code. It's a thought experiment that's all.
Beta Was this translation helpful? Give feedback.