Skip to content

Commit

Permalink
added exception class, TestModel, TestUser, DbDateTime, Model class d…
Browse files Browse the repository at this point in the history
…erived from User
  • Loading branch information
Nemoden committed Mar 22, 2012
1 parent 497bd84 commit 2e61f7b
Show file tree
Hide file tree
Showing 8 changed files with 272 additions and 97 deletions.
12 changes: 12 additions & 0 deletions DbDateTime.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php
/**
* @author Kirill "Nemoden" K
* $ Date: Thu 22 Mar 2012 07:52:09 PM VLAT $
*/

class DbDateTime extends DateTime {
private $_format = 'Y-m-d H:i:s';
public function __toString() {
return (string)parent::format($this->_format);
}
}
130 changes: 130 additions & 0 deletions Model.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
<?php
/**
* @author Kirill "Nemoden" K
* $ Date: Thu 22 Mar 2012 05:30:34 PM VLAT $
*/

/**
* hello, dolly
*/

require_once 'db.php';
require_once 'ModelException.php';

abstract class Model {

private $_dbh;

private $_is_new_instance = true;
private $_a = array(); // attributes
private $_c = array(); // changed attributes
/**
* @TODO primary key may be composite, e.g. array('id1', 'id2')
* @TODO We should be able to do something like
* @TODO Model::getByPK(array('id1' => 10, 'id2' => 20)) or just array(10,20)
*/
protected $_pk = 'id';
protected $_table = 'id';

/**
* temporary solution for date fields
* we dont bind such fields in prepare
* @TODO create DbDateTime/DbDate classes to manipulate dates, e.g. new DbDateTime('now')
*/
protected $datefields = array(
'date' => 'datetime',
);

public function __construct() {
global $dbh;
$this->_dbh = $dbh;

// we need table
if (empty($this->_table)) {
throw new ModelException('Model is not associated with any database table');
}
if (empty($this->_pk)) {
throw new ModelException('Missing table primary key');
}
}

private function formatValues($v) {
if (!isset($this->datefields[$v])) {
return ':'.$v; // bind
}
else {
return $v; // as is e.g. NOW()
}
}
private function formatKeys($k) {
return '`'.$k.'`';
}
public function save() {
if ($this->isNewRecord()) {
$keys = array_keys($this->_a);
$values = array_map(create_function('$k', 'return ":".$k;'), array_keys($this->_a));
$keys = implode(', ', array_map(array($this, 'formatKeys'), $keys));
$values = implode(', ', array_map(array($this, 'formatValues'), array_keys($this->_a)));
$sql = 'INSERT INTO '.$this->_table.' ('.$keys.') VALUES ('.$values.')';
$statement = $this->_dbh->prepare($sql);
$result = $statement->execute($this->_a);
echo 'params: ';
echo $statement->debugDumpParams();
echo 'error info: ';
echo var_export($statement->errorInfo(),1);
echo '<<<<<<<<';
if ($result) {
$this->_a[$this->_pk] = $this->_dbh->lastInsertId();
}
}
else { // update
$values = array_map(create_function('$k,$v', 'return $k."=:".$v;'), array_keys($this->_a), $this->_a);
$sql = 'UPDATE '.$this->_table.' SET '.implode(', ', $values).' WHERE '.$this->_pk.' = '.$this->_a[$this->_pk];
$statement = $this->db->prepare($sql);
$result = $statement->execute($this->_a);
}
return $result;
}

public function isNewRecord() {
return !isset($this->_a[$this->_pk]);
}

// get an attribute
public function __get($name) {
if (method_exists($this, 'get'.ucfirst($name))) {
$method = 'get'.ucfirst($name);
return $this->$method();
}
if (isset($this->_a[$name])) {
return $this->_a[$name];
}
else {
return NULL;
}
}

public function __set($name, $value) {
if ($name[0] != '_') {
$this->_a[$name] = $value;
}
}

public function __call($fn, $args) {
}

// data getters
public function getAll($conditions = NULL) {
}

public function getByPK($pk) {
$sql = 'SELECT * FROM '.$this->_table.' WHERE '.$this->_pk.' = :pk';
$statement = $this->_dbh->prepare($sql);
$restul = $statement->execute(array(':pk' => $pk));
$data = $statement->fetch(PDO::FETCH_ASSOC);
foreach ($data as $column_name => $value) {
$this->_a[$column_name] = $value;
}
return $this;
}
}
12 changes: 12 additions & 0 deletions ModelClass.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php
/**
* @author Kirill "Nemoden" K
* $ Date: Thu 22 Mar 2012 06:11:30 PM VLAT $
*/
require_once 'Model.php';

class ModelClass extends Model {
protected $_table = 'test.model_test';
protected $_pk = 'id';
}

7 changes: 7 additions & 0 deletions ModelException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?php
/**
* @author Kirill "Nemoden" K
* $ Date: Thu 22 Mar 2012 05:35:47 PM VLAT $
*/

class ModelException extends Exception {}
78 changes: 78 additions & 0 deletions TestModel.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<?php
/**
* @author Kirill "Nemoden" K
* $ Date: Thu 22 Mar 2012 05:44:34 PM VLAT $
*/

require_once 'PHPUnit/Autoload.php';
require_once 'ModelClass.php';


/**
* @backupGlobals disabled
* @backupStaticAttributes disabled
*/
class TestModel extends PHPUnit_Framework_TestCase {

public static function setUpBeforeClass() {
global $dbh;
$create_database = <<<SQL
create database if not exists `test` default character set = utf8 default collate = utf8_general_ci;
SQL;

$create_table = <<<SQL
create table if not exists `test`.`model_test` (
`id` int(11) unsigned not null auto_increment,
`string` varchar(255) not null default '',
`date` datetime not null default '0000-00-00 00:00:00',
`timestamp` timestamp,
`decimal` decimal(10,2) not null default 0.0,
`float` float not null default 0,
`int` int(11) unsigned not null default '0',
PRIMARY KEY `id` (`id`)
) ENGINE=InnoDB COMMENT='testing active record';
SQL;
try {
$dbh->beginTransaction();
$res1 = $dbh->exec($create_database);
$res2 = $dbh->exec(str_replace(PHP_EOL, '', $create_table));
if ($dbh->errorCode()) {
list($sql_error, $driver_error, $error_message) = $dbh->errorInfo();
echo $error_message;
}
$dbh->commit();
}
catch (Exception $e) {
echo $e->getMessage();
}
catch (PDOException $e) {
echo $e->getMessage();
}
}

public static function tearDownAfterClass() {
global $dbh;
# $res = $dbh->exec('drop table `model_test`');
}

public function setUp() {
}

public function tearDown() {
}

public function testCreateModel() {
$model= new ModelClass();
$model->string = 'lorem ipsum dolor';
$model->int = 10;
$model->date = 'NOW()';
$model->timestamp = 'NOW()';
$model->decimal = 10.03;
$model->float = 10/3;
$this->assertTrue($model->save(), 'save fuckup');
$this->assertEquals(10, $model->int);
echo $model->date;
$this->assertEquals(10, $model->date);
}

}
26 changes: 26 additions & 0 deletions TestUser.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php
/**
* @author Kirill "Nemoden" K
* $ Date: Thu 22 Mar 2012 05:42:11 PM VLAT $
*/

require_once 'PHPUnit/Autoload.php';

class TestUserTest extends PHPUnit_Framework_TestCase {

public function setUp() {
}

public function tearDown() {
}

public function testCreateUser() {
}

public function testGetCurrentUser() {
}

public function testUpdateUser() {
}

}
102 changes: 6 additions & 96 deletions User.php
Original file line number Diff line number Diff line change
@@ -1,111 +1,21 @@
<?php
require_once 'db.php';
/**
* hello, dolly
* @author Kirill "Nemoden" K
* $ Date: Thu 22 Mar 2012 05:33:29 PM VLAT $
*/
class User {

protected $_table = 'test.users';
protected $_pk = 'id';
private $_dbh;

private $_is_new_instance = true;
private $_a = array(); // attributes
private $_c = array(); // changed attributes

protected $attributes = array(
);
require_once 'Model.php';
class User extends Model {

public function __construct() {
global $dbh;
$this->_dbh = $dbh;
}
protected $_table = 'test.users';

public function registeredDbCriteria() {
// returns db criteria
return;
}

public function save() {
if ($this->isNewRecord()) {
$keys = array_keys($this->_a);
$values = array_map(create_function('$k', 'return ":".$k;'), array_keys($this->_a));
$sql = 'INSERT INTO '.$this->_table.' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')';
$statement = $this->_dbh->prepare($sql);
echo $sql;
$result = $statement->execute($this->_a);
if ($result) {
$this->_a[$this->_pk] = $this->_dbh->lastInsertId();
}
}
else { // update
$values = array_map(create_function('$k,$v', 'return $k."=:".$v;'), array_keys($this->_a), $this->_a);
$sql = 'UPDATE '.$this->_table.' SET '.implode(', ', $values).' WHERE '.$this->_pk.' = '.$this->_a[$this->_pk];
$statement = $this->db->prepare($sql);
$result = $statement->execute($this->_a);
}
return $result;
}

public function isNewRecord() {
return !isset($this->_a[$this->_pk]);
}

// get an attribute
public function __get($name) {
if (method_exists($this, 'get'.ucfirst($name))) {
$method = 'get'.ucfirst($name);
return $this->$method();
}
if (isset($this->_a[$name])) {
return $this->_a[$name];
}
else {
return NULL;
}
}

public function __set($name, $value) {
if ($name[0] != '_') {
$this->_a[$name] = $value;
}
}

public function getName() {
return 'Name: '.$this->_a['name'];
}

public function __call($fn, $args) {
}

// data getters
public function getAll($conditions = NULL) {
}

public function getByPK($pk) {
$sql = 'SELECT * FROM '.$this->_table.' WHERE '.$this->_pk.' = :pk';
$statement = $this->_dbh->prepare($sql);
$restul = $statement->execute(array(':pk' => $pk));
$data = $statement->fetch(PDO::FETCH_ASSOC);
foreach ($data as $column_name => $value) {
$this->_a[$column_name] = $value;
}
return $this;
return 'Test name getter: '.$this->_a['name'];
}

}

echo str_repeat(PHP_EOL, 5);
$user = new User();
$user = $user->getByPK(1);
echo $user->name;
echo str_repeat(PHP_EOL, 2);

echo str_repeat(PHP_EOL, 2);
echo 'test create user'.PHP_EOL;
$user = new User();
$user->name = 'Fedor';
$user->email = '[email protected]';
var_export($user->save());
var_export($user->name);
echo str_repeat(PHP_EOL, 5);
2 changes: 1 addition & 1 deletion db.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@
$dbh = new PDO('mysql:host=localhost;dbname=test', 'root', '');
register_shutdown_function('close_connection', $dbh); # close connection
function close_connection($dbh) {
$dbh=null;
// $dbh=null;
}

0 comments on commit 2e61f7b

Please sign in to comment.