Respect / Config

A powerful, small, deadly simple configurator and dependency injection container DSL made to be easy
http://respect.github.io/Config
Other
98 stars 7 forks source link

PHP-based lazy configuration #3

Closed alganet closed 13 years ago

alganet commented 13 years ago

Config supports only INI-based configuration files for a lot of reasons: they're fast to parse (using the native php INI parser), easy to read and very simple in structure.

INIs simplicity allows Config to reach a very sophisticated -yet minimalistic- approach to lazy loading. Each object defined is represented by an instantiator that, when executed, loads and creates the real full object and its dependencies.

Take for instance this INI file:

[foo stdClass]
name = ImAFoo

[bar stdClass]
foo = [foo]
name = ImABar

[baz stdClass]
bar = [bar]
name = ImABaz

If you ask for a Container for $container->baz, a chain reaction of lazy loading instantiators will eventually reach [foo].

A similar pure PHP file could be:

<?php

$container = new Container;

$container->foo = new stdClass;
$container->foo->name = 'ImAFoo';

$container->bar = new stdClass;
$container->bar->foo = $foo;
$container->bar->name = 'ImABar';

$container->baz = new stdClass;
$container->baz->bar = $bar;
$container->baz->name = 'ImABaz';

return $container;

This will instantiate every object independent of which is requested by the $container upon using, which is not optimal.

A very elegant solution would be porting this entire configuration to a lazy-loaded-aware namespace:

<?php

namespace Respect\Config\Lazy;

$container = new Container;

$container->foo = new stdClass;
$container->foo->name = 'ImAFoo';

$container->bar = new stdClass;
$container->bar->foo = $foo;
$container->bar->name = 'ImABar';

$container->baz = new stdClass;
$container->baz->bar = $bar;
$container->baz->name = 'ImABaz';

return $container;

A possible implementation would be a single Respect\Config\Lazy\Container class. This class would register a autoloader that automatically applies an alias to everything that begins with Respect\Config\Lazy\ pointing to Respect\Config\Instantiator.

The code remais the same, except for the new namespace at the top that sort of transports the entire context to a lazy-loaded sandbox.

I'm up to implement this on the few weeks. Any thoughts on that?

thiagophx commented 13 years ago

Great idea!

alganet commented 13 years ago

I've planned to use class_alias to make the lazy autodefining works, but it is impossible to use lsb with class_alias, since it's only a namespace-import-like feature.

Since I don't want to use eval() on Respect, I'm closing this issue and archiving this idea.