Class MyActiveRecord

Description

MyActiveRecord

A simple, speedy Object/Relational Mapper for MySQL based on Martin Fowler's ActiveRecord pattern and heavily influenced by the implementation of the same name in Ruby on Rails.

Features

- Mapping of table to class and row to object - Relationship retrieval - Data validation and error handling - PHP5 and PHP4 compatibility

License

Copyright (c) 2006, Jake Grimley <jake.grimley@mademedia.co.uk> All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

- Neither the name of Made Media Ltd. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Limitations

This class acheives simplicty of use and implementation through the following 'by-design' limitations:

1. This class talks to MySQL only.

2. Table/Class mapping is achieved by each database table being named IDENTICALLY to the MyActiveRecord subclass that will represent it (but in lowercase for compatibility reasons).

3. Every database table mapped by MyActiveRecord MUST have an autoincrementing primary-key named `id`.

Changelog 0.3 - 0.4

  1. BUG FIXES
1.1 Error is triggered when connection fails or database cannot be selected 1.2 If Class cannot be found or table cannot be found to match class script reports error instead of hanging. (this fixes bug introduced in 0.3) 1.3 Removal of error notices on save dues to presumption about existance of variables

2. FIND_CHILDREN() IMPROVEMENTS Added new paramaters to the find_children() method. First the full complement of Where, OrderBy, Limit and Offset a-la FindAll(). Second, the addition of a ForeignKey paramater. Useful if you have a table with a two foreign keys pointing to the same table, and so you need to use a different name to parent_table_id

3. ADDED FREQDIST() WHERE and LIMIT paramaters e.g. print_r( MyActiveRecord::FreqDist( 'Order', 'total_lines', "date BETWEEN '2005-01-01' AND '2006-01-01'" ) )

Located in /MyActiveRecord.0.4.php (line 90)



							
Method Summary
void add_child (mixed $strClass, [mixed $properties = null])
void add_error (string $strKey, string $strMessage)
boolean AllowNull (string $strTable, string $strField)
boolean attach (object &$obj)
void Begin ()
string Class2Table (mixed $mxd)
array Columns (string $strTable)
void Commit ()
resource Connection ()
integer Count (string $strClass, [mixed $strWhere = '1=1'])
object of &Create (strClass, $strClass, [mixed $arrVals = null])
string DbDate ([int $intTimeStamp = null])
string DbDateTime ([int $intTimeStamp = null])
void delete ()
boolean destroy ()
void detach (object &$obj)
mixed Escape (mixed $mixVal)
array FindAll (string $strClass, [mixed $mxdWhere = NULL], [string $strOrderBy = 'id ASC'], [string $intLimit = 10000], string $intOffset)
mixed FindById (string $strClass, mixed $mxdID)
array FindBySql (string $strClass, string $strSQL, [mixed $strIndexBy = 'id'])
object, FindFirst (strClass $strClass, [strWhere $strWhere = NULL], [strOrderBy $strOrderBy = 'id ASC'])
void find_attached (mixed $strClass, [mixed $strCondition = NULL])
array find_children (string $strClass, [mixed $mxdCondition = NULL], [string $strOrderBy = 'id ASC'], [integer $intLimit = 10000], integer $intOffset, [strForeignKey $strForeignKey = NULL], mixed 6)
array find_linked (string $strClass, [string $mxdCondition = null], [mixed $strOrder = null])
object object find_parent (string $strClass, [string $strForeignKey = NULL])
array FreqDist (string $strTable, string $strColumn, [string $strWhere = '1=1'], [integer $strOrder = null], [mixed $intLimit = 1000])
integer GetLen (string $strTable, string $strField)
string GetLinkTable (string $strClass1, string $strClass2)
string GetType (string $strTable, string $strField)
string get_error (string $strKey)
array get_errors ()
void get_timestamp (string $strKey)
void h (mixed $key)
boolean Insert (string $strClass, array $properties)
boolean Link (object &$obj1, object &$obj2)
boolean populate (array $arrVals)
void Prepare ()
resource Query (string $strSQL)
void RollBack ()
boolean save ()
boolean set_attached (string $strClass, array $arrID)
void set_date (string $strKey, [int $intTimeStamp = null])
void set_datetime (string $strKey, [int $intTimeStamp = null])
bool TableExists (string $strTable)
array Tables ()
int TimeStamp (string $strMySQLDate)
void to_str ()
true UnLink ($obj1 &$obj1, $obj2 &$obj2)
void Update (string $strClass, int $id, arrray $properties, boolean 3)
boolean validate_regexp (string $strKey, string $strRegExp, [string $strMessage = null])
boolean validate_uniqueness_of (string $strKey, [string $strMessage = null])
Methods
add_child (line 924)
void add_child (mixed $strClass, [mixed $properties = null])
add_error (line 1177)

Adds an error to the object. The existence of errors ensures that $object->save() will return false and will not attempt to persist the object to the database This can be used for validation of the object.

e.g.


1 if( empty( $user->first_name ) ) $user->add_error('first_name', 'First Name may not be blank!');
2 $user->save or print_r($user->get_errors)

void add_error (string $strKey, string $strMessage)
  • string $strKey: strKey the name of the invalid key/property/attribute
  • string $strMessage: strMessage a message, which you may want to report back to the user in due course
AllowNull (line 385)

finds out whether a NULL value is allowed in a specified field in a specified table

  • return: True if this field allows nulls. False if not.
  • static:
boolean AllowNull (string $strTable, string $strField)
  • string $strTable: strTable Name of database table
  • string $strField: strField Name of field in table
attach (line 946)

Attaches another object to the object

NB: You must have saved the object you want to attach before attaching it eg:


1 $post = MyActiveRecord::Create('Post');
2 $post->populate( 'title'=>'New Post' );
3 $post->save();
4 $topic->attach('post');

  • return: True on success. False on failure.
boolean attach (object &$obj)
  • object $obj: the object you wish to attach
Begin (line 773)

Static method to begin a transaction

  • static:
void Begin ()
Class2Table (line 260)

gets table representing class in database

  • return: name of table in database representing class(string) or object false if no table found
  • static:
string Class2Table (mixed $mxd)
  • mixed $mxd: either a string(class name) or an object
Columns (line 292)

Returns an array describing the specified table, or false if the table does not exist in the database.

The array contains one array per database column, keyed by the column name. To see the structure of the array you could try:


1 print_r( MyActiveRecord::Columns('your_table') );

  • return: Table columns. False if the table does not exist.
  • static:
array Columns (string $strTable)
  • string $strTable: strTable The name of the database table
Commit (line 791)

Static method to commit a transaction

  • static:
void Commit ()
Connection (line 109)

Returns a database connection to be used by the class.

If you want, you can borrow this for access to a mysql database resource: e.g.:


1 $result = mysql_Query($query, MyActiveRecord::Connection() );

This method uses the global constant MYACTIVERECORD_CONNECTION_STR for the connection paramaters. This is a string with the following format: mysql://user:passord@host/db

  • return: mysql connection
  • static:
resource Connection ()
Count (line 533)

Counts the number of rows in the database matching the optional

condition. eg:


1 print 'There are '.MyActiveRecord::Count('Person').' People in the database.';
2 print 'There are '.MyActiveRecord::Count('Person', "last_name LIKE 'Smith'").' People with the surname Smith';

  • return: Count. False if the query fails.
  • static:
integer Count (string $strClass, [mixed $strWhere = '1=1'])
  • string $strClass: strClass, the name of the class for which you want to create an object.
Create (line 510)

Creates a new object of class strClass. strClass should be an extension of MyActiveRecord. arrVals is an optional array of values.

e.g.:


1 $person = MyActiveRecord::Create('Person', array( first_name=>'Jake', last_name=>"Grimley' ) );

  • return: class strClass
  • static:
object of &Create (strClass, $strClass, [mixed $arrVals = null])
  • strClass, $strClass: the name of the subclass.
DbDate (line 195)

return a date formatted for the database

  • return: mysql format date string
  • static:
string DbDate ([int $intTimeStamp = null])
  • int $intTimeStamp: intTimeStamp A unix timestamp
DbDateTime (line 206)

return a datetime formatted for the database

  • return: mysql format datetime string
  • static:
string DbDateTime ([int $intTimeStamp = null])
  • int $intTimeStamp: intTimeStamp A unix timestamp
delete (line 907)

alias of destroy()

void delete ()
destroy (line 897)

Deletes the object from the database

eg:


1 $car = MyActiveRecord::FindById('Car', 1);
2 $car->destroy();

  • return: True on success, False on failure
boolean destroy ()
detach (line 975)

Detaches an object from the object

eg:


1 // detach old posts
2 foreach( $topic->find_attached('Post') as $post )
3 {
4 if( $post->created < mktime()-5000000 )
5 {
6 $topic->detach($post);
7 }
8 }

void detach (object &$obj)
  • object $obj: object to be detached
Escape (line 406)

Escapes a value against a field type in preparation for adding to a sql query. Escaping includes wrapping the value in single quotes

  • return: escaped value eg: 1, 'o\'reilly' etc.
  • static:
mixed Escape (mixed $mixVal)
  • mixed $mixVal: mixVal value, eg: true, 1, 'elephant' etc.
FindAll (line 609)

Returns an array of all objects of class strClass found in database

optional where, order and limit paramaters enable the results to be narrowed down. eg:


1 $cars = MyActiveRecord::FindAll('Car');
2 $cars = MyActiveRecord::FindAll('Car', "colour='red'", 'make ASC', 10);

  • return: Array of objects. Array is empty if no ojbects found
  • static:
array FindAll (string $strClass, [mixed $mxdWhere = NULL], [string $strOrderBy = 'id ASC'], [string $intLimit = 10000], string $intOffset)
  • string $strClass: strClass the name of the class for which you want objects
  • mixed $mxdWhere: mxdWhere optional SQL WHERE fragment, eg: "username='fred' AND password='123'" can also be expressed as array, e.g. array( 'username'=>'fred', password=>'123')
  • string $strOrderBy: strOrderBy optional SQL ORDER BY fragment, eg: "username ASC"
  • string $intLimit: intLimit optional integer limiting the number of records returned
  • string $intOffset: intOffset optional integer to offset the first record brought back
FindById (line 684)

Returns an object of class strClass found in database with a specific

integer ID. An array of integers can be passed in order to retrieve an array of objects with matching IDs eg:


1 $car = MyActiveRecord::FindById(15);
2 $cars = MyActiveRecord::FindById(3, 5, 13);

  • return: object, or array of objects
  • static:
mixed FindById (string $strClass, mixed $mxdID)
  • string $strClass: strClass the name of the class for which you want objects
  • mixed $mxdID: mxdID integer or array of integers
FindBySql (line 561)

Returns an array of objects of class strClass mapped from SQL query

strSQL. eg:


1 $people = MyActiveRecord::('Person', 'SELECT * FROM person ORDER BY first_name');
2 foreach( $people as $person ) print $person->first_name;

  • return: array of objects of class strClass
  • static:
array FindBySql (string $strClass, string $strSQL, [mixed $strIndexBy = 'id'])
  • string $strClass: strClass The name of the class for which you want to return objects.
  • string $strSQL: strSQL The SQL query
FindFirst (line 656)

Returns the first object of class strClass found in database

optional where, order and limit paramaters enable the results to be narrowed down eg:


1 $car = MyActiveRecord::FindFirst('Car', "colour='red'", 'model ASC');

  • return: false if no objects found
  • static:
object, FindFirst (strClass $strClass, [strWhere $strWhere = NULL], [strOrderBy $strOrderBy = 'id ASC'])
  • strClass $strClass: string, the name of the class for which you want objects
  • strWhere $strWhere: optional SQL WHERE argument, eg: "username='fred' AND password='123'"
  • strOrderBy $strOrderBy: optional SQL ORDER BY argument, eg: "username ASC"
find_attached (line 1157)

Alias of find_linked()

void find_attached (mixed $strClass, [mixed $strCondition = NULL])
find_children (line 1089)

returns array of 'child' objects.

e.g.


1 foreach( $topic->find_children('Post') as $post ) print $post->subject;

In order for the above to work, you would need to have an integer field called 'Topic_id' in your 'Post' table. MyActiveRecord will take care of the rest.

  • return: array containing objects of class strClass
array find_children (string $strClass, [mixed $mxdCondition = NULL], [string $strOrderBy = 'id ASC'], [integer $intLimit = 10000], integer $intOffset, [strForeignKey $strForeignKey = NULL], mixed 6)
  • mixed 6: optional sql condition expressed as either a sql string or an array eg: 'flagged=true' or array( 'flagged'=>1 );
  • string $strClass: strClass Name of the class of objects to return in the array
  • mixed $mxdCondition: mxdCondition Either a SQL 'WHERE' fragment or an array of paramaters that must be matched ( see FindAll() )
  • string $strOrderBy: strOrderBy a SQL ORDER BY strring fragment
  • integer $intLimit: intLimit limit on number of records to retrieve
  • integer $intOffset: intOffset if you don't want to begin with the first child you can add an offset here
  • strForeignKey $strForeignKey: if the foreign key is not parent_id but something different you can specify here
find_linked (line 1123)

returns array of 'linked' objects. (many-to-many relationship) e.g.


1 foreach( $user->find_linked('Role') as $role ) print $role->name;

In order for the above to work, you would need to have a linking table called Role_User in your database, containing the fields role_id and user_id

  • return: array containing objects of class strClass
array find_linked (string $strClass, [string $mxdCondition = null], [mixed $strOrder = null])
  • string $strClass: strClass Name of the class of objects to return in the array
  • string $mxdCondition: strCondition Optional SQL condition, e.g. 'password NOT NULL'
find_parent (line 1063)

returns 'parent' object.

e.g.


1 $topic = $post->find_parent('Topic');

In order for the above to work, you would need to have an integer field called 'Topic_id' in your 'Post' table. MyActiveRecord will take care of the rest.

  • return: of class strClass
object object find_parent (string $strClass, [string $strForeignKey = NULL])
  • string $strClass: strClass Name of the class of objects to return in the array
  • string $strForeignKey: strForeignKey Optional specification of foreign key at runtime
FreqDist (line 716)

Static Method to retrieve an array of unique values for a table/column

along with the total records featuring that unique value eg:


1 foreach( MyActiveRecord::FreqDist('Person', 'first_name') as $name=>$total )
2 {
3 print "There are $total people with the first name '$name'";
4 }

  • return: array with keys containing distinct values and values containing totals
  • static:
array FreqDist (string $strTable, string $strColumn, [string $strWhere = '1=1'], [integer $strOrder = null], [mixed $intLimit = 1000])
  • string $strTable: strTable name of database table
  • string $strColumn: strColumn name of column in table
  • string $strWhere: strOrder optional sql ORDER fragment (i.e. 'name ASC')
  • integer $strOrder: limit optional sql LIMIT to number of rows returned
GetLen (line 361)

gets the maximum allowed length of a specified field in a specified table

  • return: Maximum length of field. False if not found.
  • static:
integer GetLen (string $strTable, string $strField)
  • string $strTable: strTable Name of database table
  • string $strField: strField Name of field in table
GetLinkTable (line 440)

Given the names of two classes/database tables this method returns

the name of the table which would link them in a many-to-many relationship e.g:


1 print GetLinkTable('Driver', 'Car')

note that the linking table will order the names of the tables it links alphabetically. If you intend to have a many-to-many relationship between two classes, you need to create this table in your database. The table should have two indexed fields, providing foreign keys to the tables they link, e.g. Driver_id, Car_id

NB: This function does NOT check that the table actually exists in the database, but presumes that it does.

  • return: name of linking table
  • static:
string GetLinkTable (string $strClass1, string $strClass2)
  • string $strClass1: strClass1 name of first class/table, e.g. 'Person'
  • string $strClass2: strClass2 name of second class/table e.g. 'Role'
GetType (line 337)

Gets the 'type' of a specific field in a specified table (i.e 'int'|'float'|'date'|'char'|'text')

  • return: Field type (e.g. 'int'|'float'|'date'|'char'|'text' ). False if not found.
  • static:
string GetType (string $strTable, string $strField)
  • string $strTable: strTable Name of database table
  • string $strField: strField Name of field in table
get_error (line 1189)

Gets an error on a specified attribute.

  • return: Error Message. False if no error
string get_error (string $strKey)
  • string $strKey: strKey name of field/attribute/key
get_errors (line 1207)

Returns all errors.

  • return: Array of errors, keyed by attribute. False if there are no errors.
array get_errors ()
get_timestamp (line 1043)

Retrieves a date or datetime fields as a unix timestamp

void get_timestamp (string $strKey)
  • string $strKey: strKey property to be retrieved
h (line 1270)

Returns html-escaped property value for convenience

eg:


1 <? print $user->h('name') ?>

void h (mixed $key)
Insert (line 742)

Static method to insert a new row into the database using class strClass

and using the values in properties eg:


1 MyActiveRecord::Insert( 'Car', array('make'=>'Citroen', 'model'=>'C4', 'colour'=>'Silver') );

  • return: true or false depending upon whether insert is successful
  • static:
boolean Insert (string $strClass, array $properties)
  • string $strClass: strClass the name of the class/table
  • array $properties: properties array/hash of properties for object/row
Link (line 456)

Links two objects together. Presumes the existance of a linking table.

boolean Link (object &$obj1, object &$obj2)
  • object $obj1: An Object from a subclass of MyActiveRecord
  • object $obj2: An Object from a subclass of MyActiveRecord
populate (line 871)

Sets all object properties via an array

  • return: true if $arrVals is valid array, false if not
boolean populate (array $arrVals)
  • array $arrVals
Prepare (line 149)
void Prepare ()
Query (line 166)

Execute a SQL Query using Connection()

  • return: A MySQL result resource. False on failure.
  • static:
resource Query (string $strSQL)
  • string $strSQL: strSQL A SQL statement
RollBack (line 782)

Static method to roll back a transaction

  • static:
void RollBack ()
save (line 811)

Saves the object back to the database

eg:


1 $car = MyActiveRecord::Create('Car');
2 print $car->id; // NULL
3 $car->save();
4 print $car->id;

NB: if the object has registered errors, save() will return false without attempting to save the object to the database

  • return: true on success false on fail
boolean save ()
set_attached (line 994)

Sets all attached links via an array of IDs e.g.


1 $topic->set_attached('Post', array(1, 8, 32) );
2 $topic->set_attached('Post', $_POST['id_list']);
NB: set_attached will destroy any existing attachments for the class strClass BEFORE creating new attachments

  • return: True on success. False on failure.
boolean set_attached (string $strClass, array $arrID)
  • string $strClass: strClass class of objects to be set as attached
  • array $arrID: arrID array of object IDs
set_date (line 1024)

Sets the date of the property specified by strKey

void set_date (string $strKey, [int $intTimeStamp = null])
  • string $strKey: strKey property to be set
  • int $intTimeStamp: intTimeStamp unix timestamp
set_datetime (line 1034)

Sets the datetime of the property specified by strKey

void set_datetime (string $strKey, [int $intTimeStamp = null])
  • string $strKey: strKey property to be set
  • int $intTimeStamp: intTimeStamp unix timestamp
TableExists (line 248)

checks to see if strTable exists in database returning true or false

  • return: true/false
  • static:
bool TableExists (string $strTable)
  • string $strTable: strTable name of table to check for
Tables (line 227)

return an array containing names of tables in database

  • return: names of tables in database
  • static:
array Tables ()
TimeStamp (line 217)

return a unix timestamp from a database field

  • return: unix timestamp
  • static:
int TimeStamp (string $strMySQLDate)
  • string $strMySQLDate: mysql datetime
to_str (line 1275)
void to_str ()
UnLink (line 481)

Destroys a link between two objects where it exists

  • return: on success, false on failure
  • static:
true UnLink ($obj1 &$obj1, $obj2 &$obj2)
  • $obj1 &$obj1: An Object from a subclass of MyActiveRecord
  • $obj2 &$obj2: An Object from a subclass of MyActiveRecord
Update (line 762)

Static method to update a row in the database using class strClass

and using the values in properties eg:


1 MyActiveRecord::Update( 'Car', 1, array('make'=>'Citroen', 'model'=>'C4', 'colour'=>'Silver') );

  • static:
void Update (string $strClass, int $id, arrray $properties, boolean 3)
  • boolean 3: true or false depending upon whether update is sucessful
  • string $strClass: strClass the name of the class/table
  • int $id: id the id of the row be updated.
  • arrray $properties: properties array/hash of properties for object/row
validate_regexp (line 1229)

Validates the value of an attribute against a regular expression, adding an error to the object if the value does not match.

  • return: True if the field matches. False if it does not match.
boolean validate_regexp (string $strKey, string $strRegExp, [string $strMessage = null])
  • string $strKey: strKey name of field/attribute/key
  • string $strRegExp: strRegExp Regular Expression
  • string $strMessage: strMessage Error message to record if value does not match
validate_uniqueness_of (line 1250)

Validates the uniqueness of the value of a given field/key.

Adds error to object if field is not unique

  • return: true if field is unique, false if not
boolean validate_uniqueness_of (string $strKey, [string $strMessage = null])
  • string $strKey: strKey name of field/attribute/key
  • string $strMessage: strMessage Error message to record if value is not unique

Documentation generated on Sat, 18 Nov 2006 18:33:37 +0000 by phpDocumentor 1.2.3