Am_Record
There are 2 classes that offers easy access to database records and tables: Am_Record and Am_Table.
There is an example of model code with a utility function:
<?php
/**
* Class represents records from table ban
* {autogenerated}
* @property int $ban_id
* @property string $type
* @property string $value
* @property string $comment
* @see Am_Table
*/
class Ban extends Am_Record {
}
class BanTable extends Am_Table {
protected $_key = 'ban_id';
protected $_table = '?_ban';
/**
* Check if params matches the records in "ban" table
*
* @param array $params like (array('ip' => 'xx', 'email'=>'xx',
* 'login' => 'xxx')
* @return array() if ok, array of keys matched like array('ip','login')
*/
function findBan(array $params)
{
$db = $this->_db;
$where = array();
foreach ($params as $k => $v)
$where[] = sprintf("(`type` = %s AND %s LIKE `value` )",
$db->escape($k), $db->escape($v));
if (!$where) return array();
$arr = $db->selectCol($sql = "SELECT DISTINCT `type` FROM ?_ban WHERE " . join(" OR ", $where));
return $arr;
}
}
To define new model, you just need to define these 2 classes and put them to include path, and set $_key, $_table variables to table class. That is all. After that, you can automatically run different operations on these classes. For example:
$ban = Am_Di::getInstance()->banRecord; // create new instance of Ban class
$ban->type = 'ip';
$ban->value = "1.2.3.4";
$ban->insert();
echo $ban->pk();
echo $ban->ban_id; // the same output - primary key
$ban->comment = "new comment";
$ban->update(); // commit changes to database
$ban->refresh(); // reload record from database - it happens automatically after update and insert
$ban->delete(); // delete record from database
$banTable = Am_Di::getInstance()->banTable; // get singleton instance of BanTable class
$banTable->load(11); // loads Ban record with ban_id = 11, throws exception if not found
$banTable->findFirstByType('ip'); // @return first Ban with type = 'ip' or null if not null
$banTable->findBy(array('type'=>'ip', 'ip' => '1.2.3.4')); // @return array of Ban records
$banTable->deleteByValue('1.2.3.4'); // delete records WHERE value='1.2.3.4'
$banTable->selectObjects("SELECT * FROM ?_ban WHERE type='ip'"); // @return array of Ban records
Am_Record_WithData, Am_Table_WithData
To store additional and optional data for table records, we have defined special class and routines. If table and record subclassed from .._WithTable parents, there are special functions available. Quick samples:
$user = Am_Di::getInstance()->userTable->findFirstByEmail('xx@example.com');
$user->data()->set('xx', 'XX');
$user->update(); // updates user record and related "data()" records or ...
$user->data()->update() // updates only "data()" records
// this will create a record in ?_data table with name='xx' and value='XX' and linked to user table record with given id
unset($user);
$user = Am_Di::getInstance()->userTable->findFirstByEmail('xx@example.com');
echo $user->data()->get('xx'); // will output "XX"