Skip to content

Instantly share code, notes, and snippets.

@geekbrit
Last active May 6, 2016 10:46
Show Gist options
  • Save geekbrit/bc0d7b7da879a5404e9d to your computer and use it in GitHub Desktop.
Save geekbrit/bc0d7b7da879a5404e9d to your computer and use it in GitHub Desktop.
Lazy PDO - allows you to group all SQL in one file, and adds data accesses as services of the DB object. It is "Lazy" because accessors are prepared only when needed.
//
// Lazy PDO - register queries at startup, but only prepare them if they are actually used
//
class LPDO extends PDO
{
private $querystrings;
public function __set($property,$value)
{
if( is_object($value) )
{
$this->$property = $value;
}
else
{
$this->querystrings[$property] = $value;
}
}
public function __get($property)
{
if(property_exists($this,$property))
{
return $this->$property;
}
else
{
//echo_r($this->querystrings[$property]);
return $this->$property = $this->prepare($this->querystrings[$property]);
}
}
}
function db_connect()
{
try{
$db = new LPDO("mysql:host=".DB_SERVER.";dbname=".DB_NAME, DB_USER, DB_PASSWORD);
}
catch(PDOException $Exception) {
die( $Exception->getMessage() );
}
// example query
$db->search_inventory =
"SELECT partnumber, photo, qty, description FROM new_inv WHERE qty >= :minq ORDER BY partnumber";
// Addendum, I've started putting all the queries in their own file:
require_once 'models/queries.php';
}
// USAGE:
$db->search_inventory->execute( array( ':minq' => WHOLESALE_MINIMUM_QTY ) );
while( $row = $search-inventory->fetch(PDO::FETCH_OBJ) ){
//...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment