Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Create Runtime Code #160

Unanswered
designermonkey asked this question in Q&A
Discussion options

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?

You must be logged in to vote

Replies: 2 comments 1 reply

Comment options

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.

You must be logged in to vote
0 replies
Comment options

Hello!

How can such a class be useful at all? Why would you want to create such a class dynamically?

You must be logged in to vote
1 reply
Comment options

Personal belief that you shouldn't use functions like getenv inside OOP code. It's a thought experiment that's all.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet

AltStyle によって変換されたページ (->オリジナル) /