silexphp / Silex-Skeleton

A skeleton to get started with Silex
MIT License
780 stars 197 forks source link

Question about config setup #65

Closed pstephenson02 closed 8 years ago

pstephenson02 commented 8 years ago

Hi, and thanks in advance,

With the way this skeleton repo is setup, the front controllers (index.php and index_dev.php) first get the $app instance and then get config:

// index.php
$app = require __DIR__.'/../src/app.php';
require __DIR__.'/../config/prod.php';

In app.php, this is where (presumably all) the service providers are registered and then the $app instance is simply returned.

In my application however, some service provider config depends on the environment config. For example, I have separate doctrine config in config/test.php and config/prod.php:

// prod.php
    'db.options' => [
        'driver'   => 'pdo_mysql',
        'host'     => $parameters['mysql']['host'],
        'dbname'   => $parameters['mysql']['database'],
        'user'     => $parameters['mysql']['username'],
        'password' => $parameters['mysql']['password'],
        'charset'  => 'utf8mb4'
    ],
...
// test.php
    'db.options' => [
        'driver' => 'pdo_sqlite',
        'path'   => __DIR__.'/../../var/cache/test.db'
    ]
...

So, in app.php, when I go to register the DoctrineServiceProvider, it does not yet have the environment config to actually register the provider properly.

// app.php
$app->register(new Silex\Provider\DoctrineServiceProvider(), [ /* no config yet ;( */ ]);

How should I handle this kind of situation? Is there a way to configure the providers after registering them? Or should I just inject the config into the app.php file? I can't seem to think of a clean way to do this... any advice would be appreciated.

Thank you!

pstephenson02 commented 8 years ago

Ok, I didn't read the service provider docs very carefully, sorry! As mentioned in the docs, you can modify services after they registered as long as they haven't booted yet.

If anyone is interested, here is what I ended up doing:

$app = require __DIR__.'/../app/app.php';
$config = require __DIR__.'/../app/config/dev.php';
foreach ($config as $key => $value) {
    $app[$key] = $value;
}

where the config file keys match the service ids