Prettymad.net

PHP5 Object Persistence using PDO

There are many PHP Persistence and Database abstraction layers out there.

Well here is another one, but it dosn't try to abstract anything away from you. It has limitations, but its good to get a quick site up and going with simple DB access.

I have used this in several projects now and its very reliable for both MySQL and Oracle

Features

Limitations

Get the PDB.php source

Example Database Schema

create table AUTHOR (
  author_id not null primary_key auto_increment,
  name not null,
  update_date datetime null,
  age numeric not null
)

Simple Examples

SELECTING Data in a Collection

$authors = new PDBCollection('AUTHOR');
$authors->fetch('select * from AUTHOR');

// you can also use the select() instead of the fetch() method
$authors->select('author_id in (1,2)');

foreach($authors as $author)
{
	echo $author->name . "\n";
}

INSERTING Data

$author = new PDB('AUTHOR');
$author->name = 'John Smith';
$author->age = 5;
$author->insert();

echo $author->author_id;

UPDATING Data

$author = new PDB('AUTHOR');

// you can use the select() method
$author->select('author_id = 1');
$author->age = 5;
$author->update_date = new PDBDateTime(PDBDateTime::NOW);
$author->update();

// or the fetch() method
$author->select('select * from AUTHOR where author_id = 1');
$author->age = 5;
$author->update();

UPDATING Collection Data

$authors = new PDBCollection('AUTHOR');
$authors->fetch('select * from AUTHOR');
 
foreach($authors as $author)
{
	echo $author->name . "\n";
	$author->age = 10;
}
$authors->update();

Complex Examples

You can extend the PDBCOllection and PDB classes to your own, to add business logic to your objects

Author Class

class Author extends PDB
{
 	public $table_name = 'AUTHOR';

	public function __toString()
	{
		return sprintf('%s: %s years old', $this->name, $this->age);
	}
}

AuthorCollection Class

class AuthorCollection extends PDBCollection
{
	// what classes do we store in here?
	protected $collection_of = 'Author';
 
	// returns a list of all our authors
 	public function __toString()
	{
		$out = array();
		foreach($this as $author)
		{
			$out[] = (string)$author;
		}
		return implode("\n", $out);
	}
}

Examples

$authors = new AuthorCollection();
$authors->select('');
echo $authors;

Date handling

Dates are returned as strings, and dealt with as strings.

The PDBDateTime class helps you manage these strings, and convert them to Unix times or DateTime classes

Caching Schema data

I've added caching of schema data through the PDB_CACHE definition. It caches data to a file, so it dosn't fetch from the information_schema table every page request.

Final Note