Commit 96153540 authored by Alexander Butenko's avatar Alexander Butenko

New table() function. Improved dbObject manual

parent 9606848d
tests/ export-ignore
index.php export-ignore
...@@ -20,6 +20,6 @@ ...@@ -20,6 +20,6 @@
"php": ">=5.3.0" "php": ">=5.3.0"
}, },
"autoload": { "autoload": {
"files": ["MysqliDb.php"] "files": ["MysqliDb.php", "dbObject.php"]
} }
} }
...@@ -4,10 +4,7 @@ Please note, that this library is not pretending to be a full stack ORM but a si ...@@ -4,10 +4,7 @@ Please note, that this library is not pretending to be a full stack ORM but a si
<hr> <hr>
###Initialization ###Initialization
1. Include mysqlidb and dbObject classes. Include mysqlidb and dbObject classes. If you want to use model autoloading instead of manually including them in the scripts use autoload () method.
2. If you want to use model autoloading instead of manually including them in the scripts use autoload () method.
```php ```php
require_once ("libs/MysqliDb.php"); require_once ("libs/MysqliDb.php");
require_once ("libs/dbObject.php"); require_once ("libs/dbObject.php");
...@@ -18,24 +15,65 @@ $db = new Mysqlidb ('localhost', 'user', '', 'testdb'); ...@@ -18,24 +15,65 @@ $db = new Mysqlidb ('localhost', 'user', '', 'testdb');
dbObject::autoload ("models"); dbObject::autoload ("models");
``` ```
3. Create simple user class (models/user.php): 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.
```php
$user = dbObject::table ("users");
```
Otherwise basic model should be declared as (in case if autoload is set to 'models' directory filename should be models/user.php):
```php ```php
class user extends dbObject { class user extends dbObject {}
protected $dbTable = "users"; ```
protected $primaryKey = "id";
protected $dbFields = Array ( Class will be related to 'user' table. To change table name define correct name in the $dbTable variable:
'login' => Array ('text', 'required'),
'password' => Array ('text'), ```php
'createdAt' => Array ('datetime'), protected $dbTable = "users";
'updatedAt' => Array ('datetime'), ```
);
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
will not be working with an objects created with table() method.
###Selects
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.
##Retrieving All Records
```php
//$users = dbObject::table('users')->get ();
$users = user::get ();
foreach (users as $u) {
echo $u->login;
} }
``` ```
## Using Where Condition And A Limit
```php
$users = user::where ("login", "demo")->get (Array (10, 20));
foreach (users as $u) ...
```
##Retrieving A Model By Primary Key
```php
//$user = dbObject::table('users')->byId (1);
$user = user::byId (1);
echo $user->login;
```
dbObject will also assume that each table has a primary key column named "id". You may define a primaryKey property to override this assumption.
```php
protected $primaryKey = "userId";
```
###Insert Row ###Insert Row
1. OOP Way. Just create new object of a needed class, fill it in and call save () method. Save will return 1. OOP Way. Just create new object of a needed class, fill it in and call save () method. Save will return
record id in case of success and false in case if insert will fail. record id in case of success and false in case if insert will fail.
```php ```php
//$user = dbObject::table('users');
$user = new user; $user = new user;
$user->login = 'demo'; $user->login = 'demo';
$user->password = 'demo'; $user->password = 'demo';
...@@ -71,35 +109,8 @@ $p->seller = $user; ...@@ -71,35 +109,8 @@ $p->seller = $user;
$p->save (); $p->save ();
``` ```
After save() is call both new objects (user and product) will be saved. After save() is called both new objects (user and product) will be saved.
###Selects
Retrieving objects from the database is pretty much the same process of a get ()/getOne () execution without a need to specify table name.
All mysqlidb functions like where(), orWhere(), orderBy(), join etc are supported.
Please note that objects returned with join() will not save changes to a joined properties. For this you can use relationships.
Select row by primary key
```php
$user = user::byId (1);
echo $user->login;
```
Get all users
```php
$users = user::orderBy ('id')->get ();
foreach (users as $u) {
echo $u->login;
}
```
Using where with limit
```php
$users = user::where ("login", "demo")->get (Array (10, 20));
foreach (users as $u) ...
```
###Update ###Update
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. 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); ...@@ -116,7 +127,7 @@ $user->save ($data);
``` ```
###Delete ###Delete
Use delete() method on any loaded object. Use delete() method on any loaded object.
```php ```php
$user = user::byId (1); $user = user::byId (1);
$user->delete (); $user->delete ();
...@@ -126,7 +137,7 @@ $user->delete (); ...@@ -126,7 +137,7 @@ $user->delete ();
Currently dbObject supports only hasMany and hasOne relations. To use them declare $relations array in the model class. Currently dbObject supports only hasMany and hasOne relations. To use them declare $relations array in the model class.
After that you can get related object via variable names defined as keys. After that you can get related object via variable names defined as keys.
HasOne example: ##HasOne example:
```php ```php
protected $relations = Array ( protected $relations = Array (
'person' => Array ("hasOne", "person", 'id'); 'person' => Array ("hasOne", "person", 'id');
...@@ -141,7 +152,7 @@ HasOne example: ...@@ -141,7 +152,7 @@ HasOne example:
In HasMany Array should be defined target object name (product in example) and a relation key (userid). In HasMany Array should be defined target object name (product in example) and a relation key (userid).
HasMany example: ##HasMany example:
```php ```php
protected $relations = Array ( protected $relations = Array (
'products' => Array ("hasMany", "product", 'userid') 'products' => Array ("hasMany", "product", 'userid')
...@@ -155,6 +166,18 @@ HasMany example: ...@@ -155,6 +166,18 @@ HasMany example:
echo $p->title; echo $p->title;
} }
``` ```
### Joining tables
```php
$depts = product::join ('user');
$depts = product::join ('user', 'productid');
```
First parameter will set an object which should be joined. Second paramter will define a key. Default key is $objectName+'Id'
NOTE: Objects returned with join() will not save changes to a joined properties. For this you can use relationships.
###Timestamps ###Timestamps
Library provides a transparent way to set timestamps of an object creation and its modification: Library provides a transparent way to set timestamps of an object creation and its modification:
To enable that define $timestamps array as follows: To enable that define $timestamps array as follows:
......
...@@ -88,12 +88,27 @@ class dbObject { ...@@ -88,12 +88,27 @@ class dbObject {
* @var array * @var array
*/ */
public $errors = null; public $errors = null;
/**
* Primary key for an object. 'id' is a default value.
*
* @var stating
*/
protected $primaryKey = 'id';
/**
* Table name for an object. Class name will be used by default
*
* @var stating
*/
protected $dbTable;
/** /**
* @param array $data Data to preload on object creation * @param array $data Data to preload on object creation
*/ */
public function __construct ($data = null) { public function __construct ($data = null) {
$this->db = MysqliDb::getInstance(); $this->db = MysqliDb::getInstance();
if (empty ($this->dbTable))
$this->dbTable = get_class ($this);
if ($data) if ($data)
$this->data = $data; $this->data = $data;
} }
...@@ -174,10 +189,21 @@ class dbObject { ...@@ -174,10 +189,21 @@ class dbObject {
* @return dbObject * @return dbObject
*/ */
public static function ObjectBuilder () { public static function ObjectBuilder () {
$obj = new static; return new static;
return $obj;
} }
/**
* Helper function to create a virtual table class
*
* @param string tableName Table name
* @return dbObject
*/
public static function table ($tableName) {
$tableName = preg_replace ("/[^-a-z0-9_]+/i",'', $tableName);
if (!class_exists ($tableName))
eval ("class $tableName extends dbObject {}");
return new $tableName ();
}
/** /**
* @return mixed insert id or false in case of failure * @return mixed insert id or false in case of failure
*/ */
...@@ -471,6 +497,9 @@ class dbObject { ...@@ -471,6 +497,9 @@ class dbObject {
* @param array $data * @param array $data
*/ */
private function validate ($data) { private function validate ($data) {
if (!$this->dbFields)
return true;
foreach ($this->dbFields as $key => $desc) { foreach ($this->dbFields as $key => $desc) {
$type = null; $type = null;
$required = false; $required = false;
...@@ -531,6 +560,9 @@ class dbObject { ...@@ -531,6 +560,9 @@ class dbObject {
if (method_exists ($this, "preLoad")) if (method_exists ($this, "preLoad"))
$this->preLoad ($data); $this->preLoad ($data);
if (!$this->dbFields)
return $this->data;
foreach ($this->data as $key => &$value) { foreach ($this->data as $key => &$value) {
if ($value instanceof dbObject && $value->isNew == true) { if ($value instanceof dbObject && $value->isNew == true) {
$id = $value->save(); $id = $value->save();
......
MysqliDb -- Simple MySQLi wrapper with prepared statements MysqliDb -- Simple MySQLi wrapper and object mapper with prepared statements
<hr> <hr>
### Table of Contents ### Table of Contents
**[Initialization](#initialization)** **[Initialization](#initialization)**
**[Objects mapping](#objects-mapping)**
**[Insert Query](#insert-query)** **[Insert Query](#insert-query)**
**[Update Query](#update-query)** **[Update Query](#update-query)**
**[Select Query](#select-query)** **[Select Query](#select-query)**
...@@ -69,6 +70,10 @@ $db->setPrefix ('my_'); ...@@ -69,6 +70,10 @@ $db->setPrefix ('my_');
Next, prepare your data, and call the necessary methods. Next, prepare your data, and call the necessary methods.
### Objects mapping
dbObject.php is an object mapping library built on top of mysqliDb to provide model prepresentation functionality.
See <a href='dbObject.pm'>dbObject manual for more information</a>
### Insert Query ### Insert Query
Simple example Simple example
```php ```php
......
...@@ -16,7 +16,6 @@ ...@@ -16,7 +16,6 @@
*/ */
class user extends dbObject { class user extends dbObject {
protected $dbTable = "users"; protected $dbTable = "users";
protected $primaryKey = "id";
protected $dbFields = Array ( protected $dbFields = Array (
'login' => Array ('text', 'required'), 'login' => Array ('text', 'required'),
'active' => Array ('bool'), 'active' => Array ('bool'),
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment