DB_DataObject
[ class tree: DB_DataObject ] [ index: DB_DataObject ] [ all elements ]

Class: DB_DataObject

Source Location: /DB_DataObject-1.2/DataObject.php

Class Overview


The main "DB_DataObject" class is really a base class for your own tables classes


Author(s):

Variables

Methods


Child classes:

DB_DataObject_Generator
Generator class

Inherited Variables

Inherited Methods


Class Details

[line 145]
The main "DB_DataObject" class is really a base class for your own tables classes

// Set up the class by creating an ini file (refer to the manual for more details [DB_DataObject] database = mysql:/username:password@host/database schema_location = /home/myapplication/database class_location = /home/myapplication/DBTables/ clase_prefix = DBTables_

//Start and initialize...................... - dont forget the & $config = parse_ini_file('example.ini',true); $options = &PEAR::setStaticProperty('DB_DataObject','options'); $options = $config['DB_DataObject'];

// example of a class (that does not use the 'auto generated tables data') class mytable extends DB_DataObject { // mandatory - set the table var $_database_dsn = "mysql://username:password@localhost/database"; var $__table = "mytable"; function table() { return array( 'id' => 1, // integer or number 'name' => 2, // string ); } function keys() { return array('id'); } }

// use in the application

Simple get one row

$instance = new mytable; $instance->get("id",12); echo $instance->somedata;

Get multiple rows

$instance = new mytable; $instance->whereAdd("ID > 12"); $instance->whereAdd("ID < 14"); $instance->find(); while ($instance->fetch()) { echo $instance->somedata; }



[ Top ]


Class Variables

$N =  0

[line 169]

The Number of rows returned from a query
  • Access: public

Type:   int


[ Top ]

$_lastError =  false

[line 2355]

Last Error that has occured
  • use $this->_lastError or
$last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
  • Var: (or false)
  • Access: public

Type:   object PEAR_Error


[ Top ]



Method Detail

count   [line 1005]

int count( [bool $whereAddOnly = false])

Find the number of results from a simple query

for example

$object = new mytable(); $object->name = "fred"; echo $object->count();

  • Access: public

Parameters:

bool   $whereAddOnly     (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then we will build the condition only using the whereAdd's. Default is to build the condition using the object parameters as well.

[ Top ]

database   [line 1224]

string database( string 0)

Return or assign the name of the current database
  • Return: The name of the current database
  • Access: public

Parameters:

string   0     database name

[ Top ]

debug   [line 2307]

none debug( string $message, [string $logtype = 0], [string $level = 1])

Debugger. - use this in your extended classes to output debugging information.

Uses DB_DataObject::DebugLevel(x) to turn it on

  • Access: public

Parameters:

string   $message     - message to output
string   $logtype     - bold at start
string   $level     
  • output level

[ Top ]

debugLevel   [line 2335]

none debugLevel( [int $v = null])

sets and returns debug level eg. DB_DataObject::debugLevel(4);
  • Access: public

Parameters:

int   $v     level

[ Top ]

delete   [line 895]

bool delete( [bool $useWhere = false])

Deletes items from table which match current objects variables

Returns the true on success

for example

Designed to be extended

$object = new mytable(); $object->ID=123; echo $object->delete(); // builds a conditon $object = new mytable(); $object->whereAdd('age > 12'); $object->delete(true); // use the condition

  • Return: True on success
  • Access: public

Parameters:

bool   $useWhere     (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then we will build the condition only using the whereAdd's. Default is to build the condition only using the object parameters.

[ Top ]

escape   [line 1063]

void escape( string $string)

an escape wrapper around quote ..

can be used when adding manual queries = eg. $object->query("select * from xyz where abc like '". $object->quote($_GET['name']) . "'");

  • Return: or PEAR_Error
  • Access: public

Parameters:

string   $string     SQL Query

[ Top ]

fetch   [line 372]

boolean fetch( )

fetches next row into this objects var's

returns 1 on success 0 on failure

Example $object = new mytable(); $object->name = "fred"; $object->find(); $store = array(); while ($object->fetch()) { echo $this->ID; $store[] = $object; // builds an array of object lines. }

to add features to a fetch function fetch () { $ret = parent::fetch(); $this->date_formated = date('dmY',$this->date); return $ret; }

  • Return: on success
  • Access: public

[ Top ]

fetchRow   [line 942]

boolean fetchRow( [int $row = null])

fetches a specific row into this object variables

Not recommended - better to use fetch()

Returens true on success

  • Return: true on success
  • Access: public

Parameters:

int   $row     row

[ Top ]

find   [line 300]

int find( [boolean $n = false])

find results, either normal or crosstable

for example

$object = new mytable(); $object->ID = 1; $object->find();

will set $object->N to number of rows, and expects next command to fetch rows will return $object->N

  • Access: public

Parameters:

boolean   $n     Fetch first result

[ Top ]

get   [line 197]

int get( [string $k = null], [string $v = null])

Get a result using key, value.

for example $object->get("ID",1234); Returns Number of rows located (usually 1) for success, and puts all the table columns into this classes variables

see the fetch example on how to extend this.

if no value is entered, it is assumed that $key is a value and get will then use the first key in keys() to obtain the key.

  • Return: No. of rows
  • Access: public

Parameters:

string   $k     column
string   $v     value

[ Top ]

getDatabaseConnection   [line 2185]

object The &getDatabaseConnection( )

Gets the DB object related to an object - so you can use funky peardb stuf with it :)
  • Return: DB connection
  • Access: public

[ Top ]

getDatabaseResult   [line 2203]

object The &getDatabaseResult( )

Gets the DB result object related to the objects active query
  • so you can use funky pear stuff with it - like pager for example.. :)

  • Return: DB result object
  • Access: public

[ Top ]

getLink   [line 1710]

mixed &getLink( string $row, [string $table = null], [string $link = false])

return name from related object

There are two ways to use this, one is to set up a <dbname>.links.ini file into a static property named <dbname>.links and specifies the table joins, the other is highly dependant on naming columns 'correctly' :)

NOTE: the naming convention is depreciated!!! - use links.ini

using colname = xxxxx_yyyyyy xxxxxx = related table; (yyyyy = user defined..) looks up table xxxxx, for value id=$this->xxxxx stores it in $this->_xxxxx_yyyyy

you can also use $this->getLink('thisColumnName','otherTable','otherTableColumnName')


Parameters:

string   $row     either row or row.xxxxx
string   $table     name of table to look up value in
string   $link     name of column in other table to match

[ Top ]

getLinkArray   [line 1781]

array &getLinkArray( mixed $row, [mixed $table = null])

return a list of options for a linked table

This is highly dependant on naming columns 'correctly' :) using colname = xxxxx_yyyyyy xxxxxx = related table; (yyyyy = user defined..) looks up table xxxxx, for value id=$this->xxxxx stores it in $this->_xxxxx_yyyyy

  • Return: of results (empty array on failure)
  • Access: public

[ Top ]

getLinks   [line 1646]

boolean getLinks( [string $format = '_%s'])

load related objects

There are two ways to use this, one is to set up a <dbname>.links.ini file into a static property named <dbname>.links and specifies the table joins, the other highly dependent on naming columns 'correctly' :) using colname = xxxxx_yyyyyy xxxxxx = related table; (yyyyy = user defined..) looks up table xxxxx, for value id=$this->xxxxx stores it in $this->_xxxxx_yyyyy you can change what object vars the links are stored in by changeing the format parameter


Parameters:

string   $format     format (default _%s) where %s is the table name.

[ Top ]

groupBy   [line 487]

none|PEAR::Error groupBy( [string $group = false])

Adds a group by condition

$object->groupBy(); //reset the grouping $object->groupBy("ID DESC"); $object->groupBy("ID,age");

  • Return: - invalid args only
  • Access: public

Parameters:

string   $group     Grouping

[ Top ]

having   [line 516]

none|PEAR::Error having( [string $having = false])

Adds a having clause

$object->having(); //reset the grouping $object->having("sum(value) > 0 ");

  • Return: - invalid args only
  • Access: public

Parameters:

string   $having     condition

[ Top ]

insert   [line 665]

mixed|false insert( )

Insert the current objects variables into the database

Returns the ID of the inserted element - mysql specific = fixme?

for example

Designed to be extended

$object = new mytable(); $object->name = "fred"; echo $object->insert();

  • Return: key value or false on failure
  • Access: public

[ Top ]

joinAdd   [line 1875]

none joinAdd( [optional $obj = false], [optional $joinType = 'INNER'], [optional $joinAs = false], [optional $joinCol = false])

joinAdd - adds another dataobject to this, building a joined query.

example (requires links.ini to be set up correctly) // get all the images for product 24 $i = new DataObject_Image(); $pi = new DataObjects_Product_image(); $pi->product_id = 24; // set the product id to 24 $i->joinAdd($pi); // add the product_image connectoin $i->find(); while ($i->fetch()) { // do stuff } // an example with 2 joins // get all the images linked with products or productgroups $i = new DataObject_Image(); $pi = new DataObject_Product_image(); $pgi = new DataObject_Productgroup_image(); $i->joinAdd($pi); $i->joinAdd($pgi); $i->find(); while ($i->fetch()) { // do stuff }


Parameters:

optional   $obj     object the joining object (no value resets the join)
optional   $joinType     string 'LEFT'|'INNER'|'RIGHT'|'' Inner is default, '' indicates just select ... from a,b,c with no join and links are added as where items.
optional   $joinAs     string if you want to select the table as anther name usefull when you want to select multiple columsn from a secondary table.
optional   $joinCol     string The column on This objects table to match (needed if this table links to the child object in multiple places eg. user->friend (is a link to another user) user->mother (is a link to another user..)

[ Top ]

limit   [line 551]

none|PEAR::Error limit( [string $a = null], [string $b = null])

Sets the Limit

$boject->limit(); // clear limit $object->limit(12); $object->limit(12,10);

Note this will emit an error on databases other than mysql/postgress as there is no 'clean way' to implement it. - you should consider refering to your database manual to decide how you want to implement it.

  • Return: - invalid args only
  • Access: public

Parameters:

string   $a     limit start (or number), or blank to reset
string   $b     number

[ Top ]

links   [line 1616]

array links( )

Get the links associate array as defined by the links.ini file.

Experimental... - Should look a bit like [local_col_name] => "related_tablename:related_col_name"


[ Top ]

orderBy   [line 458]

none|PEAR::Error orderBy( [string $order = false])

Adds a order by condition

$object->orderBy(); //clears order by $object->orderBy("ID"); $object->orderBy("ID,age");

  • Return: - invalid args only
  • Access: public

Parameters:

string   $order     Order

[ Top ]

query   [line 1047]

void query( string $string)

sends raw query to database

Since _query has to be a private 'non overwriteable method', this is a relay

  • Return: or PEAR_Error
  • Access: public

Parameters:

string   $string     SQL Query

[ Top ]

raiseError   [line 2368]

error raiseError( int $message, [int $type = null], [int $behaviour = null])

Default error handling is to create a pear error, but never return it.

if you need to handle errors you should look at setting the PEAR_Error callback this is due to the fact it would wreck havoc on the internal methods!

  • Return: object
  • Access: public

Parameters:

int   $message     message
int   $type     type
int   $behaviour     behaviour (die or continue!);

[ Top ]

selectAdd   [line 593]

void selectAdd( [string $k = null])

Adds a select columns

$object->selectAdd(); // resets select to nothing! $object->selectAdd("*"); // default select $object->selectAdd("unixtime(DATE) as udate"); $object->selectAdd("DATE");

  • Access: public

Parameters:

string   $k     

[ Top ]

selectAs   [line 625]

void selectAs( [array|object|null $from = null], [string $format = '%s'], [string $tableName = false])

Adds multiple Columns or objects to select with formating.

$object->selectAs(null); // adds "table.colnameA as colnameA,table.colnameB as colnameB,......" // note with null it will also clear the '*' default select $object->selectAs(array('a','b'),'%s_x'); // adds "a as a_x, b as b_x" $object->selectAs(array('a','b'),'ddd_%s','ccc'); // adds "ccc.a as ddd_a, ccc.b as ddd_b" $object->selectAdd($object,'prefix_%s'); // calls $object->get_table and adds it all as objectTableName.colnameA as prefix_colnameA

  • Access: public

Parameters:

array|object|null   $from     the array or object to take column names from.
string   $format     format in sprintf format (use %s for the colname)
string   $tableName     table name eg. if you have joinAdd'd or send $from as an array.

[ Top ]

setFrom   [line 2036]

true setFrom( array &$from, [string $format = '%s'])

Copies items that are in the table definitions from an array or object into the current object will not override key values.
  • Return: on success or array of key=>setValue error message
  • Access: public

Parameters:

string   $format     eg. map xxxx_name to $object->name using 'xxxx_%s' (defaults to %s - eg. name -> $object->name
array   &$from     | object $from

[ Top ]

staticGet   [line 242]

object &staticGet( string $class, string $k, [string $v = null])

An autoloading, caching static get method using key, value (based on get)

Usage: $object = DB_DataObject::staticGet("DbTable_mytable",12); or $object = DB_DataObject::staticGet("DbTable_mytable","name","fred");

or write it into your extended class: function &staticGet($k,$v=NULL) { return DB_DataObject::staticGet("This_Class",$k,$v); }

  • Access: public

Parameters:

string   $class     class name
string   $k     column (or value if using keys)
string   $v     value (optional)

[ Top ]

tableName   [line 1208]

string tableName( string 0)

Return or assign the name of the current table
  • Return: The name of the current table
  • Access: public

Parameters:

string   0     table name

[ Top ]

toArray   [line 2109]

array toArray( [string $format = '%s'])

Returns an associative array from the current data (kind of oblivates the idea behind DataObjects, but is usefull if you use it with things like QuickForms.

you can use the format to return things like user[key] by sending it $object->toArray('user[%s]')

  • Return: of key => value for row
  • Access: public

Parameters:

string   $format     sprintf format for array

[ Top ]

update   [line 797]

int update( [object dataobject $dataObject = false])

Updates current objects variables into the database uses the keys() to decide how to update Returns the true on success

for example

$object = new mytable(); $object->get("ID",234); $object->email="testing@test.com"; if(!$object->update()) echo "UPDATE FAILED";

to only update changed items : $dataobject->get(132); $original = $dataobject; // clone/copy it.. $dataobject->setFrom($_POST); if ($dataobject->validate()) { $dataobject->update($original); } // otherwise an error...

  • Return: rows affected or false on failure
  • Access: public

Parameters:

object dataobject   $dataObject     (optional) - used to only update changed items.

[ Top ]

validate   [line 2141]

array validate( )

validate - override this to set up your validation rules

validate the current objects values either just testing strings/numbers or using the user defined validate{Row name}() methods. will attempt to call $this->validate{column_name}() - expects true = ok false = ERROR you can the use the validate Class from your own methods.

  • Return: of validation results or true
  • Access: public

[ Top ]

whereAdd   [line 430]

none|PEAR::Error whereAdd( [string $cond = false], [string $logic = 'AND'])

Adds a condition to the WHERE statement, defaults to AND

$object->whereAdd(); //reset or cleaer ewhwer $object->whereAdd("ID > 20"); $object->whereAdd("age > 20","OR");

  • Return: - invalid args only
  • Access: public

Parameters:

string   $cond     condition
string   $logic     optional logic "OR" (defaults to "AND")

[ Top ]

_loadConfig   [line 2406]

object an _loadConfig( )

Define the global $_DB_DATAOBJECT['CONFIG'] as an alias to PEAR::getStaticProperty('DB_DataObject','options');

After Profiling DB_DataObject, I discoved that the debug calls where taking considerable time (well 0.1 ms), so this should stop those calls happening. as all calls to debug are wrapped with direct variable queries rather than actually calling the funciton THIS STILL NEEDS FURTHER INVESTIGATION

  • Return: error object
  • Access: public

[ Top ]

__call   [line 2237]

true? __call( mixed $method, mixed $params, mixed &$return)

Overload Extension support
  • enables setCOLNAME/getCOLNAME
if you define a set/get method for the item it will be called.

otherwise it will just return/set the value. NOTE this currently means that a few Names are NO-NO's eg. links,link,linksarray, from, Databaseconnection,databaseresult

note

    • get is automatically called by toArray()
    setters return true on success. = strings on failure getters return the value!

    this fires off trigger_error - if any problems.. pear_error, has problems with 4.3.2RC2 here


    [ Top ]


    Documentation generated on Sat, 1 May 2004 00:21:02 +0200 by phpDocumentor 1.2.3. PEAR Logo Copyright © PHP Group 2004.