Written by Sean Behan on Fri Nov 10th 2017

Unfortunately PHP's PDO constructor doesn't take a database connection url (in a format that Heroku makes available as a config var) as an argument. It has its own, rather odd syntax.

However, it's easy enough to extract url parts with the parse_url method and work with those. This lets us work with each part as a variable for use in the PDO constructor.

So here is a snippet using the DATABASE_URL config var if present.. otherwise use our local development environment database connection.

$db = (function(){
    $parts = (parse_url(getenv('DATABASE_URL') ?: 'postgresql://username:password@localhost:5432/your_database_name_here'));
    extract($parts);
    $path = ltrim($path, "/");
    return new PDO("pgsql:host={$host};port={$port};dbname={$path}", $user, $pass);
})();

I used a function here because extract will create variables that I do not want polluting global scope. Using this syntax keeps extracted variables isolated to the function they are called in.. (function(){})();

Also, you will have to change the database info for you local connection.. I have hard coded it in this example.


Tagged with..
#php #pdo #heroku #deployment #database #postgres #development #environments

Just finishing up brewing up some fresh ground comments...