Skip to content

Instantly share code, notes, and snippets.

@chartjes
Created March 20, 2016 00:18
Show Gist options
  • Save chartjes/a7863b694793cab05ee1 to your computer and use it in GitHub Desktop.
Save chartjes/a7863b694793cab05ee1 to your computer and use it in GitHub Desktop.
<?php namespace OpenCFP\Provider;
use Silex\Application;
use Silex\ServiceProviderInterface;
class DatabaseServiceProvider implements ServiceProviderInterface
{
/**
* {@inheritdoc}
*/
public function register(Application $app)
{
try {
$pdo = $this->makePDOInstance($app);
} catch (\PDOException $e) {
$this->raiseDatabaseConnectionIssue();
}
$app['db'] = $pdo;
}
/**
* {@inheritdoc}
*/
public function boot(Application $app)
{
}
/**
* @param Application $app
*
* @return \PDO
*/
private function makePDOInstance(Application $app)
{
return new \PDO(
$app->config('database.dsn'),
$app->config('database.user'),
$app->config('database.password'),
[\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION]
);
}
private function raiseDatabaseConnectionIssue()
{
throw new \Exception('There was a problem connecting to the database. Make sure to use proper DSN format. See: http://php.net/manual/en/pdo.connections.php');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment