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
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)
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)
finds out whether a NULL value is allowed in a specified field in a specified table
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');
Static method to begin a transaction
gets table representing class in database
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') );
Static method to commit a transaction
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
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';
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 a date formatted for the database
return a datetime formatted for the database
alias of destroy()
Deletes the object from the database
eg:
1 $car = MyActiveRecord::FindById('Car', 1);
2 $car->destroy();
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 }
Escapes a value against a field type in preparation for adding to a sql query. Escaping includes wrapping the value in single quotes
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);
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);
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;
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');
Alias of find_linked()
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.
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
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.
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 }
gets the maximum allowed length of a specified field in a specified table
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.
Gets the 'type' of a specific field in a specified table (i.e 'int'|'float'|'date'|'char'|'text')
Gets an error on a specified attribute.
Returns all errors.
Retrieves a date or datetime fields as a unix timestamp
Returns html-escaped property value for convenience
eg:
1 <? print $user->h('name') ?>
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') );
Links two objects together. Presumes the existance of a linking table.
Sets all object properties via an array
Execute a SQL Query using Connection()
Static method to roll back a transaction
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
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
Sets the date of the property specified by strKey
Sets the datetime of the property specified by strKey
checks to see if strTable exists in database returning true or false
return an array containing names of tables in database
return a unix timestamp from a database field
Destroys a link between two objects where it exists
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') );
Validates the value of an attribute against a regular expression, adding an error to the object if the value does not match.
Validates the uniqueness of the value of a given field/key.
Adds error to object if field is not unique
Documentation generated on Sat, 18 Nov 2006 18:33:37 +0000 by phpDocumentor 1.2.3