DB_DataObject is ORM package that enables you to perform CRUD operation very easily and smoothly
we will build a simple contact list
Run the following SQL statement
CREATE TABLE `Contacts` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(255) default NULL,
`email` varchar(255) default NULL,
`phone` varchar(15) default NULL,
`address` text,
PRIMARY KEY (`id`)
)
Code the generator
Notes:
1.You need to change the values to match your environment
2.You need to give DataObjects folder 777 permission
CreateDataObjects.php
<?php
require_once('PEAR.php');
$options = &PEAR::getStaticProperty('DB_DataObject','options');
$options = array(
'database' => 'mysql://elkersh:password@localhost/contacts_db',
'schema_location' => '/home/mohammad/www/DataObjects',
'class_location' => '/home/mohammad/www/DataObjects',
'require_prefix' => 'DataObjects/',
'class_prefix' => 'DataObjects_',
);
require_once("DB/DataObject/Generator.php");
DB_DataObject::debugLevel(1);
$generator = new DB_DataObject_Generator;
$generator->start();
Now run this file by going to the address
http://localhost/CreateDataObjects.php
if you navigate the DataObjects folder you will find that some files are created for use by DB_DataObject.
I will separate the configuration. Save the following
conf.php
<?php
include_once('DB/DataObject.php' );
include_once('DB/DataObject/Cast.php');
//define database configuration values
$options = &PEAR::getStaticProperty('DB_DataObject','options');
$options = array(
'database' => 'mysql://root:@localhost/blog',
'schema_location' => '/home/mohammad/www/test/blog/1/DataObjects',
'class_location' => '/home/mohammad/www/test/blog/1/DataObjects',
'require_prefix' => 'DataObjects/',
'class_prefix' => 'DataObjects_',
);
We need to preform the usual database operations here is how.
Add New Record
Add.php
<?php
require_once('conf.php');
$contact = DB_DataObject::factory( 'Contacts' );
$contact->name="Mohammad Elkersh";
$contact->email="mohamad@example.com";
$contact->phone="009878765";
$contact->address="My Block - My Street - My Building - My Apartment";
$contact->insert();
Edit.php
<?php
require_once('conf.php');
$contact = DB_DataObject::factory( 'Contacts' );
contact->get(1);
$contact->name="Mohammad";
$contact->email="new@new.com";
$contact->phone="0000000";
$contact->address="My Address";
$contact->update();
Delete.php
<?php
require_once('conf.php');
$contact = DB_DataObject::factory( 'Contacts' );
$contact->get(1);
$contact->delete();
List.php
<?php
require_once('conf.php');
$contact = DB_DataObject::factory( 'Contacts' );
$contact->find();
while($contact->fetch()) {
echo "".$contact->name."\n";
}