Skip to content

Instantly share code, notes, and snippets.

@Lewiscowles1986
Last active February 4, 2018 16:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Lewiscowles1986/01eab610d6a94dad98d4de44701dab89 to your computer and use it in GitHub Desktop.
Save Lewiscowles1986/01eab610d6a94dad98d4de44701dab89 to your computer and use it in GitHub Desktop.
12-factor-app PHP DB URL parsing made simple
<?php
/**
* @license AGPL
* @license https://opensource.org/licenses/AGPL-3.0 GNU Affero General Public License
* @author "Lewis Cowles" <lewiscowles@me.com>
*/
/**
* small function that gets details from url using PHP built-in function
*
* @param string $name the name of the environment variable containing DB details from Heroku / 12-factor style ENV var
*/
function get_details_from_env_url($name='DATABASE_URL') {
return parse_url(getenv($name));
}
/**
* basic interface for extracting Database details (so you can pull from config file, env, or json whatever)
*/
interface DBDetails {
function getHost() : string;
function getScheme() : string;
function getDBName() : string;
function getUser() : string;
function getPass() : string;
function getPort() : int;
}
/**
* Basic method to provide static single-method PDO
*
* @param DBDetails $creds Object implementing this interface
* @param array $opts Array of Options to PDO
*/
function DB(DBDetails $creds, array $opts=[]) : \PDO {
$port = !empty($creds->getPort()) ? ";port={$creds->getPort()}" : "";
return new \PDO(
"{$creds->getScheme()}:host={$creds->getHost()}{$port};dbname={$creds->getDBName()}",
$creds->getUser(),
$creds->getPass(),
$opts
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment