/php_record

Simple Active Record implementation in PHP.

Primary LanguagePHP

Record – Simple Active Record implementation in PHP

This code is combination of Model class taken from Green Framework and DB_DataContainer and MDB2_DataContainer2 classes.

Usage

Simple example.

try {
    $dbh = new PDO('sqlite:/tmp/record.sqlite');
} catch(PDOException $e) {
    print $e->getMessage();
}

class Person extends Record {
    
    protected $first_name;
    protected $last_name;
    protected $age;
    
    public static $has_one  = array('computer');
    public static $has_many = array('cars');
    
    public function beforeSave() {
        if (120 > $this->age()) {
            return false;
        } else {
            return true;
        }
    };

}

class Computer extends Record {
    
    protected $mark;
    protected $person_id;
    protected static $belongs_to = array('person');

}

class Car extends Record {
    
    protected $mark;
    protected $person_id;
    protected static $belongs_to = array('person');
    
}

Person::connection($dbh);

$mika = new Person();
$mika->firstName('Mika');
$mika->lastName('Tuupola');
$mika->age(100);
$mika->save();

$mac = new Computer();
$mac->mark('Mac');
$mika->computer($mac);

printf('Guy called %s %s is %d years old.', 
        $mika->firstName(),
        $mika->lastName(),
        $mika->age());
        
$bmw = new Car();
$bmw->mark('BMW');

$audi = new Car();
$audi->mark('Audi');

$fisker = new Car();
$fisker->mark('Fisker Karma');

$mika->cars(array($bmw, $audi, $fisker));
$mika->save();
        
$all_mika = Person::findByFirstName('Mika');
$one_mika = Person::findByFirstName(':one', 'Mika');

$apple = $one_mika->computer();

$three_cars = $one_mika->cars();