<?php
/*
http://coolpenguin.net/persistclass
for updates, documentation, tutorials
*/
require('demo1-connection.php');
// preparation for the demo (inserting a row with id = 1)
class TestTable extends PersistClass {
protected $sqlTableName = 'TESTTABLE';
protected $sqlPrimaryKey = 'testid';
}
$id = 1;
try {
$newTestTable = new TestTable($id);
} catch(NoResultException $e) {
$newTestTable = new TestTable();
$newTestTable->setId($id);
$newTestTable->insertDb();
}
// REGISTERING MULTIPLE CONNECTIONS
// creating more onnections
/*
$anotherConnection = new DbConnectionMysql();
$anotherConnection->connect('anotherhost', 'demouser', 'demopassword', 'anotherdemodatabase');
*/
// register other connection into pool named as 'other'
/*
DbConnectionPool::instance()->registerConnection($anotherConnection, 'other');
*/
// getting the non-default connections
/*
$otherCon = DbConnectionPool::instance()->getConnection('other');
*/
// defining a class to use the 'other' connection
class TestTableOther extends PersistClass {
protected $sqlConnectionName = 'other';
protected $sqlTableName = 'TESTTABLE';
protected $sqlPrimaryKey = 'testid';
}
// PERSISTENCE DEMO
// adding extra initializing to table classes
class TestTableSomeExtra extends PersistClass {
protected $sqlTableName = 'TESTTABLE';
protected $sqlPrimaryKey = 'testid';
protected function init() {
// code for initializing when reading an object from the database
}
}
// nesting classes to deal with more complex db data structures, eg. joined tables.
class TestAttachment extends Persistclass {
protected $sqlTableName = 'TESTATTACHMENT';
protected $sqlPrimaryKey = 'attachmentid';
}
class TestTableWithNestedClass extends PersistClass {
protected $sqlTableName = 'TESTTABLE';
protected $sqlPrimaryKey = 'testid';
private $attachments;
protected function init() {
$sql = 'SELECT attachmentid from TESTATTACHMENT where testid = '. $this->getId();
$ids = DbConnectionPool::instance()->getCon()->queryFirstColumnSet($sql);
$attach = new TestAttachment();
$this->attachments = $attach->getItemsWithIds($ids);
// note: lazy instantiation is better in most cases to prevent unnecessary lookups
}
public function getAttachments() {
return $this->attachments;
}
}
// instantiating objects dinamicaly - without defining a class
$dyn = new PersistClass();
$dyn->setSqlTableName('TESTTABLE');
$dyn->setSqlPrimaryKey('testid');
$id = 1;
$dyn->initId($id);
$dyn->setData('testcolumn', 'data is set');
$dyn->updateDb();
// cloning connection object. Since the connection object is responsible for holding the resultset, nesting db lookups can cause problems
$con = DbConnectionPool::instance()->getConnection();
$con2 = $con->cloneConnection();
echo 'Test successful';
?>
|