function displayEveryone() { $person = new Person(); $people = $person->getAllLikeMe(); dbm_debug('info', 'Found ' . count($people) . ' entries.'); foreach ($people as $person) { dbm_debug("info", "Person {$person->ID}: {$person->firstname} {$person->lastname}"); } return $people; }
public function __construct() { dbm_debug('info', "Trying to create a new " . get_class($this)); if ($this->is_constructor_blocked()) { dbm_debug('info', "Found constructor block. Stopping"); } else { $this->blockConstructor(); $foo = new $this->sibling(); $this->unBlockConstructor(); } // End if }
protected $table_name = 'myBooks'; protected $table_columns = array('isbn' => "varchar(20)", 'author' => "tinytext", 'title' => "tinytext", 'pubyear' => "year"); protected $autoprimary = TRUE; } $pub = new collection(1); dbm_debug('heading', "Loading \"{$pub->name}\" from the first example."); dbm_debug('info', "Default ordering"); $books = $pub->getLinks("Book"); foreach ($books as $book) { dbm_debug('data', "{$book->title} ({$book->pubyear})"); } dbm_debug('info', "Order by year ascending"); $books = $pub->getLinks("Book", "ORDER BY pubyear ASC"); foreach ($books as $book) { dbm_debug('data', "{$book->title} ({$book->pubyear})"); } dbm_debug('info', "Order by year descending"); $books = $pub->getLinks("Book", "ORDER BY pubyear DESC"); foreach ($books as $book) { dbm_debug('data', "{$book->title} ({$book->pubyear})"); } dbm_debug('info', "Order by year ascending with limit (kind of a hack)"); $books = $pub->getLinks("Book", "ORDER BY pubyear ASC LIMIT 1"); foreach ($books as $book) { dbm_debug('data', "{$book->title} ({$book->pubyear})"); } dbm_debug('info', "Order by year descending with limit (kind of a hack)"); $books = $pub->getLinks("Book", "ORDER BY pubyear DESC LIMIT 1"); foreach ($books as $book) { dbm_debug('data', "{$book->title} ({$book->pubyear})"); }
function save($force = FALSE) { $defs = $this->getTableDefs(); $columns = $this->getTableColumns($defs); $allclean = array(); $savedata = array(); $key = $this->findTableKey(); $a = $this->getAttribs(); if (!isset($a[$key]) || $a[$key] == NULL) { // This object has never been saved, force save regardless of status // It's very probable that this object is being linked to or is linking another object and needs an ID $force = TRUE; // Exclude the ID in the sql query. This will trigger an auto_increment ID to be generated $excludeID = TRUE; dbm_debug("info deep", "This " . get_class($this) . " is new, and we are saving all attributes regardless of status"); } else { // Object has been saved before, OR a new ID was specified by the constructor parameters. // either way, we need to include the ID in the SQL statement so that the proper row gets set, // or the proper ID is used in the new row $excludeID = FALSE; } $magicput_needs_rewrite = TRUE; foreach ($columns as $col) { if ($this->status[$col] != "clean" || $force || $magicput_needs_rewrite) { if (isset($a[$col])) { $savedata[$col] = $a[$col]; } } } if (count($savedata) >= 1) { if (!$excludeID) { $savedata[$key] = $a[$key]; } $id = $this->sqlMagicPut($savedata); if ($id) { // Successful auto_increment Save $this->attributes[$key] = $id; // Set all statuses to clean. $this->status = array_fill_keys(array_keys($this->status), "clean"); return TRUE; } else { if ($id !== FALSE) { // We are not working with an auto_increment ID // Set all statuses to clean. $this->status = array_fill_keys(array_keys($this->status), "clean"); return TRUE; } else { // ID === false, there was an error die("Save Failed!\n" . mysql_error()); return FALSE; } } } }
$info = array('firstname' => 'John', 'lastname' => 'Doe'); dbm_debug('data', $info); // Make the call to set the attributes from the info. $person->attribs($info); // Returns the attributes back into the $attribs variable $attribs = $person->attribs(); // The above could have been done in one line: // $attribs = $person->attribs($info); // I separated it for illustrative purposes dbm_debug('info', "First Name: " . $attribs['firstname']); dbm_debug('info', "Last Name: " . $attribs['lastname']); dbm_debug('info', "Full Name: " . $attribs['fullname']); dbm_debug('info', "Reverse Name: " . $attribs['lastfirst']); dbm_debug('info', "Showing the data actually stored in the object:"); $person->dumpview(true); dbm_debug('info', "Showing attributes."); dbm_debug('data', $person->attribs()); dbm_debug('heading', "With overload operators"); dbm_debug('info', "The overload operators __set() and __get() work with attribs(), so they will automatically work with your custom attribs function:"); $person = new Person(); // $person is now blank, it doesn't have any info from the previous example dbm_debug('info', "Setting the first and last name of the person."); $person->firstname = "John"; $person->lastname = "Doe"; dbm_debug('info', "First Name: " . $person->firstname); dbm_debug('info', "Last Name: " . $person->lastname); dbm_debug('info', "Full Name: " . $person->fullname); dbm_debug('info', "Reverse Name: " . $person->lastfirst); dbm_debug('heading', "Showing the data actually stored in the object."); $person->dumpview(true); dbm_debug('heading', "Showing attributes."); dbm_debug('data', $person->attribs());
$m->lastname = "Doe"; $m->save(); $mid = $m->getPrimary(); dbm_debug('info', "When saving the second example Person, it received a primary key value of {$mid}"); $r = new Restaurant(); $r->name = "Joe's Place"; $r->rating = 5; $r->owner = $p; $r->manager = $m; $r->save(); dbm_debug('info', 'Done saving examples.'); $rid = $r->getPrimary(); dbm_debug('info', "When saving the example restaurant, it received a primary key value of {$rid}, which can be used later to load the Restaurant from the database."); dbm_debug('info', "Like this:"); $joes = new Restaurant($rid); dbm_debug('info', 'The restaurant object has been created, but there won\'t be any database traffic until you try to access its attributes:'); // This next line will trigger the load from the database echo "{$joes->name} is a {$joes->rating}-star restaurant."; dbm_debug('info', 'Similarly, the external table objects, in this case the owner and manager, have been created, but they won\'t load themselves from the database until you try to access their attributes.'); // This next line will trigger the owner object to load itself from the database echo "{$joes->name} is owned by {$joes->owner->firstname} {$joes->owner->lastname}."; // This next line will trigger the manager object to load itself from the database echo "{$joes->name} is run by {$joes->manager->firstname} {$joes->manager->lastname}."; dbm_debug('info', "Notice that the returned attribs include a Person object as the 'owner' and 'manager' attributes. You get the actual objects, not just their primary keys"); dbm_debug('data', $joes->attribs()); dbm_debug('data', $joes->owner->attribs()); dbm_debug('data', $joes->manager->attribs()); dbm_debug('info', "The dumpview command runs on the AmortizeFeatures level, and is ignorant of externals. It shows you how the external data will be saved to the database."); $joes->dumpview(true); $joes->owner->dumpview(true); $joes->manager->dumpview(true);
<?php class RingNode extends AmortizeInterface { protected $table_name = "ringnodes"; protected $table_columns = array('payload' => 'tinytext'); protected $externals = array('next' => 'RingNode'); protected $autoprimary = true; } class RingHandle extends AmortizeInterface { protected $table_name = "rings"; protected $table_columns = array('name' => 'tinytext'); protected $externals = array('currentnode' => 'RingNode'); protected $autoprimary = true; } $handle = new RingHandle(1); dbm_debug('heading', $handle->currentnode->payload); $handle->currentnode = $handle->currentnode->next; $handle->save();
dbm_debug('info', 'Creating a new newBook(4), this should NOT generate any database traffic.'); $poky = new newBook(4); dbm_debug('info', 'Verifying that the proper primary key is set to 4, also no database traffic should be generated'); if ($poky->getPrimary() == 4) { dbm_debug('info', 'Verified.'); } else { dbm_debug('error', 'Failed.'); } dbm_debug('info', 'Getting the attributes for the newBook, this should trigger a load.'); echo "{$poky->title}, by {$poky->author}: <img src=\"{$poky->photoURL}\" />\n"; dbm_debug('info', 'Creating a new newBook(4), this should NOT generate any database traffic.'); $poky2 = new newBook(4); dbm_debug('info', 'Saving the newBook(4), this should NOT overwrite the current DB entry'); $poky2->save(); dbm_debug('info', 'Checking data integrity'); $poky3 = new newBook(4); if ($poky->title == $poky3->title) { dbm_debug('info', 'data preserved.'); } else { dbm_debug('error', 'data corrupted'); } dbm_debug('heading', "Testing external objects"); $review = new Review(); $review->subject = new Book(4); dbm_debug('info', $review->subject->title); $review->subject->title .= " follows his nose home"; dbm_debug('info', $review->subject->title); $review->subject->save(); $poky = new Book(4); dbm_debug('info', $poky->title);
<?php class Person extends AmortizeInterface { protected $table_name = 'people'; protected $table_columns = array('firstname' => 'varchar(20)', 'lastname' => 'varchar(20)'); protected $autoprimary = true; // Full name generator public function attribs($info = null, $force = null) { $info = parent::attribs($info, $force); $info['fullname'] = "{$info['firstname']} {$info['lastname']}"; return $info; } } class Restaurant extends AmortizeInterface { protected $autoprimary = true; protected $table_name = 'restaurants'; protected $table_columns = array('name' => 'varchar(20)', 'rating' => 'tinyint'); protected $externals = array('owner' => 'Person', 'manager' => 'Person'); } class Dining extends AmortizeInterface { protected $table_name = 'restaurants'; } $foo = new Dining(); dbm_debug('data', $foo->getTableDefs());
class FormattingTest extends Amortize { protected $table_name = 'format_testing'; protected $table_columns = array('options' => "set('foo','bar','boo','baz')", 'someDate' => 'date', 'pointInTime' => 'datetime', 'aTime' => 'time', 'testBool' => 'boolean'); protected $autoprimary = true; } $test = new FormattingTest(); dbm_debug('info', 'Setting the info:'); $options = array('foo' => true, 'bar' => false, 'invalidoption' => true, 'baz' => true); $test->options = $options; $test->someDate = "Last Tuesday"; $test->pointInTime = "Saturday, 5:00 PM"; $test->aTime = "Noon"; $test->testBool = true; dbm_debug('info', 'Doing the save: The SQL statement should have sql-compatible formats for our info.'); $test->save(); dbm_debug('info', 'Loading back out of the database:'); $id = $test->getPrimary(); $newTest = new FormattingTest($id); dbm_debug('data', $newTest->attribs()); dbm_debug('heading', "End of test."); // Code below deals with dropping the the testing table. if (isset($_POST['drop']) && $_POST['drop'] == "Drop Testing Table") { $test->dropTable(); } ?> <form method="POST"> <div class="info">You can drop the test table if you want to see the table recreated on the next run, or if you just want to clean the testing DB</div> <input name="drop" type="submit" value="Drop Testing Table" /> </form>
/** * Makes every attempt to succeed at doing the query you ask it to do. * This function will attempt the query and react by modifying the database to match your definitions if the query fails */ protected function makeQueryHappen($query) { $tableDefs = $this->table_defs; $tableName = $this->getTableName(); dbm_debug("regular query", $query); $sql = $this->getSQLConnection(); $result = amtz_query($query, $sql); if (!$result) { // We have a problem here dbm_debug("system error", mysql_error()); if (!$this->table_exists()) { dbm_debug("error", "Query Failed . . . table {$tableName} doesn't exist."); $this->createTable(); } else { if ($tableDefs[$tableName] != $this->getActualTableDefs()) { dbm_debug("error", "Query Failed . . . table {$tableName} needs updating."); $this->updateTable($tableDefs); } } dbm_debug("regular query", $query); $result = amtz_query($query, $sql); if (!$result) { // We tried :( dbm_debug("error", "Query Retry Failed . . . table {$tableName} could not be fixed."); return FALSE; } } // If we got to here, that means we have got a valid result! switch (strtoupper(first_val(explode(' ', $query)))) { case 'SELECT': $returnVal = array(); while ($row = mysql_fetch_assoc($result)) { $returnVal[] = $row; } return $returnVal; break; case 'INSERT': case 'REPLACE': return mysql_insert_id($sql); break; } }
protected function createTable($foo = null) { // First: take care of the obligations to this function call. parent::createTable($foo); // Next: attempt to make a delete trigger if our configuration allows it. if ($this->createTriggers) { $mapName = $this->getFullTableName(); $fromTableName = $this->from->getFullTableName(); $fromPrimary = $this->from->findTableKey(); $toTableName = $this->to->getFullTableName(); $toPrimary = $this->to->findTableKey(); $sql = $this->getSQLConnection(); $mapFromCol = MAP_FROM_COL; $mapToCol = MAP_TO_COL; $fromQuery = <<<QUERY \t\t\t\tCREATE TRIGGER {$mapName}_FromDeleteTrigger \t\t\t\t AFTER DELETE ON {$fromTableName} \t\t\t\t FOR EACH ROW \t\t\t\t DELETE FROM {$mapName} WHERE {$mapFromCol}=OLD.{$fromPrimary} QUERY; $toQuery = <<<QUERY \t\t\t\tCREATE TRIGGER {$mapName}_ToDeleteTrigger \t\t\t\t AFTER DELETE ON {$toTableName} \t\t\t\t FOR EACH ROW \t\t\t\t DELETE FROM {$mapName} WHERE {$mapToCol}=OLD.{$toPrimary} QUERY; dbm_debug("system query", $fromQuery); mysql_query($fromQuery, $sql) or die($fromQuery . "\n\n" . mysql_error()); dbm_debug("system query", $toQuery); mysql_query($toQuery, $sql) or die($toQuery . "\n\n" . mysql_error()); } }