slimphp-api / slim-api

Command line interface for generating API end points with Slim
MIT License
11 stars 1 forks source link

Add db connection to skeleton template #10

Closed gabriel403 closed 9 years ago

gabriel403 commented 9 years ago

Currently there's no connection class/dependency in the container setup in the final app, need something like this for eloquent

$container['database.config.file'] = function($container) {
    $cwd = getcwd();
    $locator = new Symfony\Component\Config\FileLocator([$cwd . DIRECTORY_SEPARATOR]);
    return $locator->locate('phinx.yml', $cwd, true);
};

$container['database.config'] = function($container) {
    $configFilePath = $container['database.config.file'];
    $config = Phinx\Config\Config::fromYaml($configFilePath);
    return $config;
};

$container['environment.name'] = function($container) {
    $name = getenv('ENV') ?: 'development';
    return $name;
};

$container['database.configForEloquent'] = function($container) {
    $config         = $container['database.config'];
    $environment    = $container['environment.name'];
    $phinxConfig    = $container['database.config']->getEnvironment($environment);
    $eloquentConfig = [
        'driver'    => $phinxConfig['adapter'],
        'host'      => $phinxConfig['host'],
        'database'  => $phinxConfig['name'],
        'username'  => $phinxConfig['user'],
        'password'  => $phinxConfig['pass'],
        'charset'   => $phinxConfig['charset'],
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ];

    return $eloquentConfig;
};

$container['database.connectEloquent'] = function($container) {
    $config  = $container['database.configForEloquent'];
    $manager = new \Illuminate\Database\Capsule\Manager;
    $manager->addConnection($config);
    // Set the event dispatcher used by Eloquent models... (optional)
    $manager->setEventDispatcher(new \Illuminate\Events\Dispatcher(new \Illuminate\Container\Container));
    // Make this Capsule instance available globally via static methods... (optional)
    $manager->setAsGlobal();
    // Setup the Eloquent ORM... (optional; unless you've used setEventDispatcher())
    $manager->bootEloquent();

    return $manager;
};

and then something to call $container['database.connectEloquent'] each run (middleware?)