Passed
Pull Request — master (#526)
by Michael
06:45
created

DataObject::getById()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 8
nc 2
nop 2
dl 0
loc 15
ccs 0
cts 9
cp 0
crap 6
rs 10
c 1
b 0
f 0
1
<?php
2
3
/**
4
 * DataObject is the base class for all the database access classes. Each
5
 * "DataObject" holds one record from the database, and provides functions to
6
 * allow loading from and saving to the database.
7
 *
8
 * Note: This requires the database tables to be named the same as the classes,
9
 * and the database tables must have an "id" column. Simple views can be used
10
 * as a way of aliasing to allow for a transition period.
11
 *
12
 * @author Simon Walker
13
 */
14
abstract class DataObject
15
{
16
	/**
17
	 * @var int ID of the object
18
	 */
19
	protected $id = 0;
20
21
	/**
22
	 * @var bool
23
	 * TODO: we should probably make this a read-only method rather than public - why should anything external set this?
24
	 */
25
	public $isNew = true;
26
27
	/**
28
	 * @var PdoDatabase
29
	 */
30
	protected $dbObject;
31
32
	public function setDatabase(PdoDatabase $db)
33
	{
34
		$this->dbObject = $db;
35
	}
36
    
37
	/**
38
	 * Gets the database associated with this data object.
39
	 * @return PdoDatabase
40
	 */
41
	public function getDatabase()
42
	{
43
		return $this->dbObject;   
44
	}
45
46
	/**
47
	 * Retrieves a data object by it's row ID.
48
	 * @param int $id
49
	 * @param PdoDatabase $database
50
	 * @return DataObject|null
51
	 */
52
	public static function getById($id, PdoDatabase $database)
53
	{
54
		$statement = $database->prepare("SELECT * FROM `" . strtolower(get_called_class()) . "` WHERE id = :id LIMIT 1;");
55
		$statement->bindValue(":id", $id);
56
57
		$statement->execute();
58
59
		$resultObject = $statement->fetchObject(get_called_class());
60
61
		if ($resultObject != false) {
62
			$resultObject->isNew = false;
63
			$resultObject->setDatabase($database);
64
		}
65
66
		return $resultObject;
67
	}
68
69
	/**
70
	 * Saves a data object to the database, either updating or inserting a record.
71
	 */
72
	abstract public function save();
73
74
	/**
75
	 * Retrieves the ID attribute
76
	 */
77
	public function getId()
78
	{
79
		return $this->id;
80
	}
81
82
	/**
83
	 * Deletes the object from the database
84
	 */
85
	public function delete()
86
	{
87
		$statement = $this->dbObject->prepare(
88
			"DELETE FROM `"
89
			. strtolower(get_called_class())
90
			. "` WHERE id = :id;");
91
92
		$statement->bindValue(":id", $this->id);
93
		$statement->execute();
94
95
		$this->id = 0;
96
		$this->isNew = true;
97
	}
98
	
99
	public function getObjectDescription()
100
	{
101
		return '[' . get_called_class() . " " . $this->getId() . ']';	
102
	}
103
}
104