Class: Generic

A generic object class for extending. Makes it easy to write quick object wrappers
for your database tables, reducing the amount of SQL work you need to do, as well
as the amount of SQL that ends up in your code. Also helps keep that SQL code in
your libraries (ie. extended methods of your Generic child class), and not in
your boxes/forms.

New in 2.0:

- Added new methods: setCurrent, makeObj, set, val, pkey, exists, save, cascade,
and load.
- The load() method enables the creation of several objects at once, including
the relationships between them, in a single INI file.


Usage Example


<?php

loader_import 
('saf.Database.Generic');

class 
NewsStory extends Generic {
    function 
MyClass () {
        
parent::Generic ('news_story''id');
    }

    
// we want it to default to sorting by date/time
    
function orderBy ($ord 'ts desc') {
        
parent::orderBy ($ord);
    }
}

// create a quick temporary database table
db_execute ('create table news_story (
    id int not null auto_increment primary key,
    title char(72) not null,
    author char(72) not null,
    ts datetime not null,
    section char(32) not null,
    body text not null,
    index (section, ts, author)
)'
);

$s = new NewsStory;

// insert some stories
$id $s->add (array (
    
'title' => 'Test Story 1',
    
'author' => 'Agent Smith',
    
'ts' => date ('Y-m-d H:i:s'),
    
'section' => 'Sports',
    
'body' => 'Testing one two...',
));
$id $s->add (array (
    
'title' => 'Test Story 2',
    
'author' => 'Agent Smith',
    
'ts' => date ('Y-m-d H:i:s'),
    
'section' => 'Sports',
    
'body' => 'Testing three four...',
));

// retrieve the first 5 sports stories
$s->limit (5);
$list $s->find (array ('section' => 'Sports'));
$s->clear (); // remove the limit again

echo template_simple (
    
'{loop obj[items]}
    <p><strong>{title}</strong> {author}<br />{body}</p>
    {end loop}'
,
    array (
'items' => $list)
);

// get a specific story
$story $s->get ($list[0]->id);
info ($story);

// drop the temporary table
db_execute ('drop table news_story');

?>

Return to Top



Properties


$connection

  • Access: public

Contains the database connection resource.


$path

  • Access: public

Path to the Berkeley Database.


$mode

  • Access: public

Mode to use when opening the database (corresponds to
the modes available to the dba_open () function.


$handler

  • Access: public

The database implementation used (db2, db3, gdbm, etc.).


$persistent

  • Access: public

A 1 or 0 (true or false, and true by default), specifying whether
to establish a persistent connection or not.


$transactions = 0

  • Access: public

Boolean value denoting whether to enable transactions in the
current database.


$driver

  • Access: public

Contains the name of the database driver being used.


$host

  • Access: public

Contains the name of the database host.


$name

  • Access: public

Contains the name of the database being used.


$user

  • Access: public

Contains the username used to connect to the current database.


$pass

  • Access: public

Contains the password used to connect to the current database.


$dbd

  • Access: private

Contains the loaded database driver.


$error = false

Contains an error message, if one occurs.


$sql = ''

  • Access: public

Contains the SQL query to be executed.


$rows

  • Access: public

Contains the number of rows returned by the previous fetch() call.


$lastid

  • Access: public

Contains the lastid() of the last insert query sent to the execute()
method.


$tables = false

  • Access: public

Contains a list of tables in the database. Set by getTables().


$pearEmu = false


$sequenceFormat = '%s_seq'


$fetchMode = DB_FETCHMODE_OBJECT


$result = ''

  • Access: public

Contains the result identifier for the current execution.


$field = ''

  • Access: public

Currently unused.


$_fetchModeFunctions = array (
        
DB_FETCHMODE_ASSOC        => 'mysql_fetch_array',
        
DB_FETCHMODE_OBJECT        => 'mysql_fetch_object',
    )


$typemap = array (
        
'bpchar'                    => 'text',
        
'char'                        => 'text',
        
'varchar'                    => 'text',
        
'text'                        => 'textarea',

        
'date'                        => 'date',
        
'time'                        => 'time',
        
'timestamp'                    => 'datetime',
        
'.*'                        => 'text',

        
// arrays
        // booleans
        // blobs
    
)

  • Access: public

Contains a key/value list of database types (regular
expressions are used here to save repeating ourselves) and their
corresponding MailForm widget types.


$column

  • Access: public

Column name of the facet.


$title

  • Access: public

Dispaly name of the facet.


$extra

  • Access: public

Extra info about the facet.


$tableObj

  • Access: public

DatabaseTable object.


$items = array ()

  • Access: public

List of options in the facet.


$type = 'normal'

  • Access: public

Type of the facet. Possible values are 'normal', 'self_ref', 'date', and 'time'.
This value is auto-determined by compile(), but can be customized as well.


$table = ''

Table name.


$fields = array ()

List of all fields for this table.


$pkey = ''

Primary key field.


$fkey = ''

Optional name of a foreign key field, for use in simplified find() calls.


$listFields = '*'

The list of fields to return on find(). Default is '*' to return all fields.


$isAuto = true

Whether the pkey is auto-incrementing or not.


$orderBy = ''

Contains the "order by" clause value (ie. "name asc") for calls to find().


$groupBy = ''

Contains the "group by" clause value (ie. "name asc") for calls to find().


$limit = false

Contains the "limit" clause value for calls to find().


$offset = false

Contains the "offset" clause value for calls to find().


$invalid = array ()

A list of invalid fields and their corresponding error messages,
from the previous validate() call.


$usePermissions = false

Determines whether to automatically add access control to find(), count(),
and get() calls.


$multilingual = false

Enables automatic translation of items pulled from the database through
Sitellite's new multilingual capabilities.


$_cascade = array ()

This is the list of external types to cascade deletions across. In the
case of external objects, the keys are the object names and the values
are the referencing field in the external object's table. In the case
of join tables for many-to-many relationships, the keys are simply
numeric and the value is an array containing the join table name and the
name of the field referring to the current object's primary key field.

Ordinarily, these values are set automatically via the load() method,
and the relationships are defined in an INI file.

Return to Top



Methods


Generic ($table = '', $pkey = '', $fkey = '', $listFields = '*', $isAuto = true)

Constructor method.


_join ($list, $op = ' AND ')

  • Access: private


_end ()

  • Access: private


&translate (&$obj)

  • Access: public
  • Return: object or array of objects

Translates an object or array of objects based on the current language
of the visitor.


listFields ($listFields = '*')

  • Access: public

Set or reset the $listFields property.


foreignKey ($fkey = '')

  • Access: public

Set or reset the $foreignKey property.


orderBy ($orderBy = '')

  • Access: public

Set or reset the $orderBy property.


groupBy ($groupBy = '')

  • Access: public

Set or reset the $groupBy property.


limit ($limit = false)

  • Access: public

Set or reset the $limit property.


offset ($offset = false)

  • Access: public

Set or reset the $offset property.


clear ()

  • Access: public

Reset all of the above properties.


find ($fid)

  • Access: public
  • Return: array of objects

Find objects with the specified values. $fid can be the ID of a field
from the $fkey column, or a hash or object with a list of clauses
(ie. array ('section' => 'Sports')).

To create more complex queries, such as:

WHERE foo = ? AND (bar = ? OR bar = ? OR bar = ?)

you can use 2-dimensional arrays, such as this:

$this->find (array (
'foo' => 'value',
'bar' => array ('one', 'two', 'three'),
));


getList ($fid)

Deprecated, use find().


single ()

  • Access: public
  • Return: object

This method acts the same way db_single() does, which is to return the
first result of a find() call only, as an object. This method takes
the same parameters as find(). Returns false if there is no matching
row.


shift ()

  • Access: public
  • Return: string

This method acts the same way db_shift() does, which is to return the
first column value of the result of a find() call only, as a string.
This method takes the same parameters as find(). Returns false if
there is no matching row.


count ($fid)

  • Access: public
  • Return: integer

Returns the number of matches for a given set of parameters. Accepts the
same input as find().


query ($sql, $bind = array ())

  • Access: public
  • Return: array of objects

Allows you to pass SQL queries directly to the database, which are
first passed to SimpleTemplate with $this. This allows for queries
like 'SELECT * FROM {table} WHERE {pkey} = ?'.


&get ($id)

  • Access: public
  • Return: object

Returns a single object with the specified $id.


add ($struct)

  • Access: public
  • Return: boolean

Inserts a record into the database with the specified values. If $isAuto
is set, returns the primary key of the new record.


modify ($id, $struct)

  • Access: public
  • Return: boolean

Updates the specified record with the new values.


remove ($id = false)

  • Access: public
  • Return: boolean

Deletes the specified record from the database.


makeStruct ($vals)

  • Access: public
  • Return: array hash

Makes a valid array hash out of the specified $vals,
using the $fields list as a reference.


addRule ($name, $rule, $msg = '')

  • Access: public
  • Return: boolean

Adds a MailForm rule that can be used by the validate() method
to ensure that any incoming data passes certain "correctness"
rules.


validate ($vals)

  • Access: public
  • Return: boolean

Validates the specified data list against the list of rules
added via addRule(). Lists the invalid rules in the $invalid
list, and returns true or false whether the values passed or
not.


setCurrent (&$obj)

  • Access: public

Sets the currently "active" object. The current object can be used for
internal method calls without having to specify the ID or values of an
object to those methods.


&makeObj ()

  • Access: public
  • Return: object reference

Returns the currently active object.


set ($name, $value)

  • Access: public

Sets a property of the currently active object.


val ($name)

  • Access: public
  • Return: mixed

Retrieves a property of the currently active object.


pkey ()

  • Access: public
  • Return: mixed

Retrieves the primary key value of the currently active object.


exists ($id)

  • Access: public
  • Return: boolean

Determines whether an item with the specified primary key exists.


save ()

  • Access: public
  • Return: boolean

Saves the currently active object to the database.


cascade ($id)

  • Access: private

Deletes all of the entries from adjacent tables. Called by the remove()
method automatically, based on the relations defined which have the
cascade value turned on.


load ($app, $pkg)

  • Access: public
  • Return: boolean

Loads a series of objects that are dynamically generated from an INI file.
The INI file lives in the 'lib' folder of an app, and is named $pkg.ini.php.
If the 'lib' folder is writeable, a static copy of the generated code will
be saved to lib/_$pkg.php and be loaded next time. The static copy is
automatically regenerated upon any change to the INI file or to this file
(Generic.php).

The INI file defines which objects to make available, and the relations
between them. For example, for a shopping cart you might define objects for
Product, Category, Option, and Order. The relations might be that a Product
belongs to one or more Categories and Orders, and one or more Options belong
to a Product.

The benefit of using this technique is that it provides convenience methods
for controlling the relationships between objects. Specifically, for each
relation, the following three methods are defined (in both directions):

- set{Object} (&$Object)
- unset{Object} (&$object)
- get{Object}s ()

Where {Object} is the name of the related object. So for a Product, you
would have setCategory, unsetCategory, getCategories, and so on. For a
Category you would have setProduct, unsetProduct, and getProducts. However,
for Options, since they belong to only one Product, the getProducts method
is actually named getProduct and returns just the one Product.

Loading packages in this way is also seamlessly integrated into the Loader
class as well, simply call:

loader_import ('myapp.Objects');

And you will have generated and imported the objects defined in
inc/app/myapp/lib/Objects.ini.php just like that.

The INI format is as follows:



Additional relationship types '11' (one-to-one) and 'tree' (via self-
referencing columns) are planned to be added in a future release.

Return to Top

Copyright © 2008 Sitellite CMS Project

Powered by Sitellite 5.0 Content Management System