Contributing / DB_Object
| From: | fabien dot marty at free dot fr | Date: | Mon, 29 Apr 2002 08:34:13 +0000 |
| Subject: | Contributing / DB_Object | ||
| Groups: | php.pear.dev | ||
| Request: | Send a blank email to pear-dev+get-5874@lists.php.net to get a copy of this message | ||
Hello,
I would like contribute to PEAR with a new package (DB_Object).
Why ?
-----
When you want to save a real object (with properties, methods...) in
a database, I think you have two possibilities :
- First idea : you serialize() the object and you put it in database. The
problem is that you can't change anything to the class definition (new
properties or methods) because you would loose your records in database.
- Second idea : you make a table with one field for one (object) property and
you write sql query like :
'INSERT INTO table SET field1 = "$this->field1", field2 =
"$this->field2",
field3 = "$this->field3"...'
and the same think for 'UPDATE' queries and 'SELECT' queries.
The problem is that it's boring to write and to maintain when you add properties
to your objects...
DB_Object ?
-----------
DB_Object is a class with static methods to write these boring sql queries in
order
to insert/update/load objects to database. It use DB to access to database.
Synopsis
--------
#
# mysql table : 'user'
#
CREATE TABLE personne (
id bigint(20) NOT NULL auto_increment,
name tinytext NOT NULL,
birth_year int(4) NOT NULL default '0',
PRIMARY KEY (id),
KEY id (id)
);
<?php
class user
{
var $id;
var $name;
var $birth_year;
(...) // methods...
}
(...) // you make a DB connection to the database ($db)
(...) // you make a user object ($user)
// to add the $user object into database as a new record
DB_Object::insert($db, "user", $user);
$user->name = "Bob"; // you change the name
$user->birth_year = 1970; // you change the birth_year
// to update only the name
DB_Object::update($db, "id=$user->id", $user, "name", "only");
in database
// to update the entire record in database (not the key 'id')
DB_Object::update($db, "id=$user->id", $user, "id");
(...)
$sql = "SELECT * FROM user WHERE id=4"; // sql query to access to user
which id=4
// load the user as a real 'user' object (with methods...)
$user2 = DB_Object::load($db, "user", $sql, new user());
(...)
$sql = "SELECT * FROM user WHERE birth_year=1970"; // sql query to access
to all users which birth_year=1970
// return an array which each element is a real 'user' object (with
methods...)
$users_1970 = DB_Object::multipleLoad($db, "user", $sql, new user());
?>
Source Code
-----------
The source code (with PEAR coding standards) is available at :
http://www.esub2.com/DB_Object.php.txt
Conclusion
----------
I would be very proud and happy to receive comments or questions about
this package in order to improve it...
Thanks,
Fabien MARTY
(fabien.marty@free.fr)