Here’s a little script I’ve wanted to make for a while, but have only just finally got the motivation to work on.

It’s a lightweight Database wrapper with functions similar to Ruby on Rails’ ActiveRecord.

When I discovered the __call() method I wanted to make my own version in PHP, so here it is!

It supports most basic functions, all based on the MySQL set of PHP functions, no other wrapper is required (PEAR etc.). There is not (yet?) any automatic mysql_real_escape_string or anything, although that could easily be added if required, my assumption is you’ve done that kind of thing already before passing anything to it.

$db = new DB('mysql://username:password@server:port/database');
$people = $db->table('people');
$companies = $db->table('companies');

$company = $company->find_by_name_like('%test%');

$person = $people->create(
    'name' => 'Dom',
    'company_id' => $company->id,
    'created_date' => date('Y-m-d H:i:s')

$id = $people->lastId();
$dom = $people->find($id);

print $person->name;
// Dom

print $dom->name;
// Dom

$dom = $person;
$new_users = $person->find_by_created_date_before(date('Y-m-d H:i:s', strtotime('1 hour ago')));

foreach ($new_users as $user) {
  // loop through all the users with a create date more than 1 hour ago
  if (!$company->find($user->company_id)) {
    // and delete any that don't have a company associated with them

It’s only a first draft, so any comments, questions or pointing out any typo’s in the code, (yeah, there are likely to be a few…) would be muchly appreciated.

This work is free under the Creative Commons Share Alike 2.0 license.


DB_0.1.tar.gz (4.84Kb)

Edit: Think next on my list is TextMate syntax highlighting and maybe the non-default template…

3 Replies to “DB”

  1. This looks acetastic. I’d been wondering about putting together some similar stuff after a brief venture into RoR last year, but this looks already pretty comprehensive in terms of the DB side of things! I’ll try and remember to check back for updates. 🙂

    P.S. Slight typo on line 31 of your example code there. Oh, and the CC note in the post too.

  2. Thanks Aaron, I’ll try and get a message to you if I make any major changes.

    Typo’s fixed, thanks!

    I am going to write a bit more of a description, document the code better and produce some more examples this week, might be useful as the above examples were rushed…

  3. Hi. I found your class via snipplr.com. Although it looks quite cool I can’t handle it 🙁 I am just diggin’ into OOP. Is there any help I can get? Even don’t know how to select just an ASSOC out of my table.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.