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

Variable Expanding #1

Closed dre1080 closed 13 years ago

dre1080 commented 13 years ago

Currently config like this in php.ini:

[PDO]
db_driver = "mysql"
db_host   = "localhost"
db_name   = "somedb"
db_user   = "root"
db_pass   = ""
db_dsn    = "[db_driver]:host=[db_host];dbname=[db_name]"

[Mongo]
db_driver = "mongodb"
db_host   = "localhost"
db_name   = "something"
db_user   = "user"
db_pass   = "pass"
db_server = "[db_driver]://[db_user]:[db_pass]@[db_host]/[db_name]"

returns php notice errors of undefined indexes. and in the end db_dsn => :host=;dbname= db_server => ://:@/

alganet commented 13 years ago

Actually, the usage is a little bit different. Each [section] creates a new object or array, and variable expanding works only for variables outside sections. I would probably write something like this:

pdo_driver = "mysql"
pdo_host = "localhost"
pdo_name = "somedb"
pdo_user = "root"
pdo_pass = ""
pdo_dsn = "[pdo_driver]:host=[pdo_host];dbname=[pdo_name]"

mongo_driver = "mongodb"
mongo_host = "localhost"
mongo_name = "something"
mongo_user = "user"
mongo_pass = "pass"
mongo_server = "[mongo_driver]://[mongo_user]:[mongo_pass]@[mongo_host]"

[pdoConnection PDO]
dsn = [pdo_dsn]
username = [pdo_user]
password = [pdo_pass]

[mongoConnection Mongo]
server = [mongo_server]

[mongoDb MongoDb]
conn = [mongoConnection]

And then:

<?php

$container = new Respect\Config\Container("config.ini");
$mongoDb = $container->mongoDb;
$db = $container->pdoConnection;

In this sample, the keys outside sections acts as variables that you can use elsewhere. The [sections] represent objects, so [pdoConnection PDO] means $pdoConnection = new PDO. The keys for each section are parameters for that object. They can be constructor params, properties or method calls.

The PDO object for example has a constructor with the params $dsn, $username and $password. Respect\Config then uses the keys inside the config section to instantiate that object.

The usage is similar to PHP itself, but the main advantage is that every object declaration is lazy loaded. The PDO connection will only start when you try to get it from the container.

Let me know if I can help you with anything else. Thanks!

dre1080 commented 13 years ago

thanks! :)