Skip to content

Commit f3a7e61

Browse files
committed
Merge pull request #240 from avbdr/master
dbObject updates
2 parents f07da2a + 4e7ae96 commit f3a7e61

File tree

7 files changed

+153
-54
lines changed

7 files changed

+153
-54
lines changed

.gitattributes

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
tests/ export-ignore
2+
index.php export-ignore

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,6 @@
2020
"php": ">=5.3.0"
2121
},
2222
"autoload": {
23-
"files": ["MysqliDb.php"]
23+
"files": ["MysqliDb.php", "dbObject.php"]
2424
}
2525
}

dbObject.md

Lines changed: 97 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,7 @@ Please note, that this library is not pretending to be a full stack ORM but a si
44
<hr>
55
###Initialization
66

7-
1. Include mysqlidb and dbObject classes.
8-
9-
2. If you want to use model autoloading instead of manually including them in the scripts use autoload () method.
10-
7+
Include mysqlidb and dbObject classes. If you want to use model autoloading instead of manually including them in the scripts use autoload () method.
118
```php
129
require_once ("libs/MysqliDb.php");
1310
require_once ("libs/dbObject.php");
@@ -18,24 +15,65 @@ $db = new Mysqlidb ('localhost', 'user', '', 'testdb');
1815
dbObject::autoload ("models");
1916
```
2017

21-
3. Create simple user class (models/user.php):
18+
Each database table could be easily mapped into a dbObject instance. If you do not want to create model for a simple table its object could be simply created with a table() method.
19+
```php
20+
$user = dbObject::table ("users");
21+
```
2222

23+
Otherwise basic model should be declared as (in case if autoload is set to 'models' directory filename should be models/user.php):
2324
```php
24-
class user extends dbObject {
25-
protected $dbTable = "users";
26-
protected $primaryKey = "id";
27-
protected $dbFields = Array (
28-
'login' => Array ('text', 'required'),
29-
'password' => Array ('text'),
30-
'createdAt' => Array ('datetime'),
31-
'updatedAt' => Array ('datetime'),
32-
);
25+
class user extends dbObject {}
26+
```
27+
28+
Class will be related to 'user' table. To change table name define correct name in the $dbTable variable:
29+
30+
```php
31+
protected $dbTable = "users";
32+
```
33+
34+
Both objects created throw new class file creation of with table() method will have the same set of methods available. Only exception is that relations, validation or custom model methods
35+
will not be working with an objects created with table() method.
36+
37+
38+
###Selects
39+
Retrieving objects from the database is pretty much the same process as a mysqliDb get()/getOne() methods without a need to specify table name. All mysqlidb functions like where(), orWhere(), orderBy(), join etc are supported.
40+
41+
##Retrieving All Records
42+
43+
```php
44+
//$users = dbObject::table('users')->get ();
45+
$users = user::get ();
46+
foreach (users as $u) {
47+
echo $u->login;
3348
}
3449
```
50+
51+
## Using Where Condition And A Limit
52+
```php
53+
$users = user::where ("login", "demo")->get (Array (10, 20));
54+
foreach (users as $u) ...
55+
```
56+
57+
##Retrieving A Model By Primary Key
58+
59+
```php
60+
//$user = dbObject::table('users')->byId (1);
61+
$user = user::byId (1);
62+
echo $user->login;
63+
```
64+
65+
dbObject will also assume that each table has a primary key column named "id". You may define a primaryKey property to override this assumption.
66+
67+
```php
68+
protected $primaryKey = "userId";
69+
```
70+
71+
3572
###Insert Row
36-
1. OOP Way. Just create new object of a needed class, fill it in and call save () method. Save will return
73+
1. OOP Way. Just create new object of a needed class, fill it in and call save () method. Save will return
3774
record id in case of success and false in case if insert will fail.
3875
```php
76+
//$user = dbObject::table('users');
3977
$user = new user;
4078
$user->login = 'demo';
4179
$user->password = 'demo';
@@ -71,35 +109,8 @@ $p->seller = $user;
71109
$p->save ();
72110
```
73111

74-
After save() is call both new objects (user and product) will be saved.
75-
76-
###Selects
77-
78-
Retrieving objects from the database is pretty much the same process of a get ()/getOne () execution without a need to specify table name.
79-
80-
All mysqlidb functions like where(), orWhere(), orderBy(), join etc are supported.
81-
Please note that objects returned with join() will not save changes to a joined properties. For this you can use relationships.
82-
83-
Select row by primary key
84-
85-
```php
86-
$user = user::byId (1);
87-
echo $user->login;
88-
```
89-
90-
Get all users
91-
```php
92-
$users = user::orderBy ('id')->get ();
93-
foreach (users as $u) {
94-
echo $u->login;
95-
}
96-
```
112+
After save() is called both new objects (user and product) will be saved.
97113

98-
Using where with limit
99-
```php
100-
$users = user::where ("login", "demo")->get (Array (10, 20));
101-
foreach (users as $u) ...
102-
```
103114

104115
###Update
105116
To update model properties just set them and call save () method. As well values that needed to by changed could be passed as an array to the save () method.
@@ -116,7 +127,7 @@ $user->save ($data);
116127
```
117128

118129
###Delete
119-
Use delete() method on any loaded object.
130+
Use delete() method on any loaded object.
120131
```php
121132
$user = user::byId (1);
122133
$user->delete ();
@@ -126,7 +137,7 @@ $user->delete ();
126137
Currently dbObject supports only hasMany and hasOne relations. To use them declare $relations array in the model class.
127138
After that you can get related object via variable names defined as keys.
128139

129-
HasOne example:
140+
##HasOne example:
130141
```php
131142
protected $relations = Array (
132143
'person' => Array ("hasOne", "person", 'id');
@@ -141,7 +152,7 @@ HasOne example:
141152

142153
In HasMany Array should be defined target object name (product in example) and a relation key (userid).
143154

144-
HasMany example:
155+
##HasMany example:
145156
```php
146157
protected $relations = Array (
147158
'products' => Array ("hasMany", "product", 'userid')
@@ -155,6 +166,18 @@ HasMany example:
155166
echo $p->title;
156167
}
157168
```
169+
170+
### Joining tables
171+
```php
172+
$depts = product::join ('user');
173+
$depts = product::join ('user', 'productid');
174+
```
175+
176+
First parameter will set an object which should be joined. Second paramter will define a key. Default key is $objectName+'Id'
177+
178+
179+
NOTE: Objects returned with join() will not save changes to a joined properties. For this you can use relationships.
180+
158181
###Timestamps
159182
Library provides a transparent way to set timestamps of an object creation and its modification:
160183
To enable that define $timestamps array as follows:
@@ -163,6 +186,31 @@ protected $timestamps = Array ('createdAt', 'updatedAt');
163186
```
164187
Field names cant be changed.
165188

189+
### Array Fields
190+
dbObject can automatically handle array type of values. Optionaly you can store arrays in json encoded or in pipe delimeted format.
191+
To enable automatic json serialization of the field define $jsonFields array in your modal:
192+
```php
193+
protected $jsonFields = Array ('operations');
194+
```
195+
To enable pipe delimetered storage of the field define $arrayFields array in your modal:
196+
```php
197+
protected $arrayFields = Array ('sections');
198+
```
199+
200+
```php
201+
$user = new user;
202+
$user->login = 'admin';
203+
$user->options = Array ('canReadNews', 'canPostNews', 'canDeleteNews');
204+
$user->sections = Array ('news', 'companyNews');
205+
$user->save ();
206+
...
207+
$user = user::byId (1);
208+
print_r ($user->options);
209+
```
210+
Following code will store 'options' variable as a json string in the database and will return back an array on load.
211+
Same with 'sections' variable except that it will be stored in pipe delimetered format.
212+
213+
166214
###Validation and Error checking
167215
Before saving and updating the row dbObject do input validation. In case validation rules are set but their criteria is not met
168216
then save() will return an error with its description. For example:
@@ -189,6 +237,8 @@ Validation rules must be defined in $dbFields array.
189237
First parameter is a field type. Types could be the one of following: text, bool, int, datetime or a custom regexp.
190238
Second parameter is 'required' and its defines that following entry field be always defined.
191239

240+
NOTE: All variables which are not defined in the $dbFields array will be ignored from insert/update statement.
241+
192242
###Array as return values
193243
dbObject can return its data as array instead of object. To do that ArrayBuilder() function should be used in the beginning of the call.
194244
```php
@@ -222,4 +272,4 @@ Object could be easily converted to a json string or an array.
222272

223273
###Examples
224274

225-
Please look for a use examples in tests/dbObjectTests.php file and test models inside the tests/models/ directory
275+
Please look for a use examples in <a href='tests/dbObjectTests.php'>tests file</a> and test models inside the <a href='tests/models/'>test models</a> directory

dbObject.php

Lines changed: 40 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -88,12 +88,27 @@ class dbObject {
8888
* @var array
8989
*/
9090
public $errors = null;
91+
/**
92+
* Primary key for an object. 'id' is a default value.
93+
*
94+
* @var stating
95+
*/
96+
protected $primaryKey = 'id';
97+
/**
98+
* Table name for an object. Class name will be used by default
99+
*
100+
* @var stating
101+
*/
102+
protected $dbTable;
91103

92104
/**
93105
* @param array $data Data to preload on object creation
94106
*/
95107
public function __construct ($data = null) {
96108
$this->db = MysqliDb::getInstance();
109+
if (empty ($this->dbTable))
110+
$this->dbTable = get_class ($this);
111+
97112
if ($data)
98113
$this->data = $data;
99114
}
@@ -174,10 +189,21 @@ public static function ArrayBuilder () {
174189
* @return dbObject
175190
*/
176191
public static function ObjectBuilder () {
177-
$obj = new static;
178-
return $obj;
192+
return new static;
179193
}
180194

195+
/**
196+
* Helper function to create a virtual table class
197+
*
198+
* @param string tableName Table name
199+
* @return dbObject
200+
*/
201+
public static function table ($tableName) {
202+
$tableName = preg_replace ("/[^-a-z0-9_]+/i",'', $tableName);
203+
if (!class_exists ($tableName))
204+
eval ("class $tableName extends dbObject {}");
205+
return new $tableName ();
206+
}
181207
/**
182208
* @return mixed insert id or false in case of failure
183209
*/
@@ -271,6 +297,7 @@ private function byId ($id, $fields = null) {
271297
private function getOne ($fields = null) {
272298
$results = $this->db->getOne ($this->dbTable, $fields);
273299
$this->processArrays ($results);
300+
$this->data = $results;
274301
$this->processWith ($results);
275302
if ($this->returnType == 'Array')
276303
return $results;
@@ -296,6 +323,7 @@ private function get ($limit = null, $fields = null) {
296323
$results = $this->db->get ($this->dbTable, $limit, $fields);
297324
foreach ($results as &$r) {
298325
$this->processArrays ($r);
326+
$this->data = $r;
299327
$this->processWith ($r);
300328
if ($this->returnType == 'Object') {
301329
$item = new static ($r);
@@ -446,6 +474,7 @@ private function processWith (&$data) {
446474
return;
447475
foreach ($this->_with as $w)
448476
$data[$w] = $this->$w;
477+
449478
$this->_with = Array();
450479
}
451480

@@ -468,6 +497,9 @@ private function processArrays (&$data) {
468497
* @param array $data
469498
*/
470499
private function validate ($data) {
500+
if (!$this->dbFields)
501+
return true;
502+
471503
foreach ($this->dbFields as $key => $desc) {
472504
$type = null;
473505
$required = false;
@@ -528,6 +560,9 @@ private function prepareData () {
528560
if (method_exists ($this, "preLoad"))
529561
$this->preLoad ($data);
530562

563+
if (!$this->dbFields)
564+
return $this->data;
565+
531566
foreach ($this->data as $key => &$value) {
532567
if ($value instanceof dbObject && $value->isNew == true) {
533568
$id = $value->save();
@@ -556,8 +591,9 @@ private function prepareData () {
556591
}
557592

558593
private static function dbObjectAutoload ($classname) {
559-
$filename = "models/". $classname .".php";
560-
include ($filename);
594+
$filename = static::$modelPath . $classname .".php";
595+
if (file_exists ($filename))
596+
include ($filename);
561597
}
562598

563599
/*

readme.md

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1-
MysqliDb -- Simple MySQLi wrapper with prepared statements
1+
MysqliDb -- Simple MySQLi wrapper and object mapper with prepared statements
22
<hr>
33
### Table of Contents
44
**[Initialization](#initialization)**
5+
**[Objects mapping](#objects-mapping)**
56
**[Insert Query](#insert-query)**
67
**[Update Query](#update-query)**
78
**[Select Query](#select-query)**
@@ -69,6 +70,10 @@ $db->setPrefix ('my_');
6970

7071
Next, prepare your data, and call the necessary methods.
7172

73+
### Objects mapping
74+
dbObject.php is an object mapping library built on top of mysqliDb to provide model prepresentation functionality.
75+
See <a href='dbObject.md'>dbObject manual for more information</a>
76+
7277
### Insert Query
7378
Simple example
7479
```php

tests/dbObjectTests.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,13 @@ function createTable ($name, $data) {
121121
exit;
122122
}
123123

124+
$product = product::with('userId')->byId(5);
125+
if (!is_object ($product->data['userId'])) {
126+
echo "Error in with processing in getOne object";
127+
exit;
128+
}
129+
130+
124131
$products = product::ArrayBuilder()->with('userId')->get(2);
125132
if (!is_array ($products[0]['userId'])) {
126133
echo "Error in with processing in get";

tests/models/user.php

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616
*/
1717
class user extends dbObject {
1818
protected $dbTable = "users";
19-
protected $primaryKey = "id";
2019
protected $dbFields = Array (
2120
'login' => Array ('text', 'required'),
2221
'active' => Array ('bool'),

0 commit comments

Comments
 (0)