AkObject | --AkBaseModel | --AkAssociatedActiveRecord | --AkActiveRecord
Located in File: /AkActiveRecord.php
See the mapping rules in table_name and the full example in README.txt for more insight.
== Creation ==
Active Records accepts constructor parameters either in an array or as a list of parameters in a specific format. The array method is especially useful when you're receiving the data from somewhere else, like a HTTP request. It works like this:
You can also use a parameter list initialization.:
$user = new User('name->', 'David', 'occupation->', 'Code Artist');
And of course you can just create a bare object and specify the attributes after the fact:
== Conditions ==
Conditions can either be specified as a string or an array representing the WHERE-part of an SQL statement. The array form is to be used when the condition input is tainted and requires sanitization. The string form can be used for statements that doesn't involve tainted data. Examples:
The <tt>authenticateUnsafely</tt> method inserts the parameters directly into the query and is thus susceptible to SQL-injection attacks if the <tt>$user_name</tt> and <tt>$password</tt> parameters come directly from a HTTP request. The <tt>authenticateSafely</tt> method, on the other hand, will sanitize the <tt>$user_name</tt> and <tt>$password</tt> before inserting them in the query, which will ensure that an attacker can't escape the query and fake the login (or worse).
When using multiple parameters in the conditions, it can easily become hard to read exactly what the fourth or fifth question mark is supposed to represent. In those cases, you can resort to named bind variables instead. That's done by replacing the question marks with symbols and supplying a hash with values for the matching symbol keys:
== Accessing attributes before they have been type casted ==
Some times you want to be able to read the raw attribute data without having the column-determined type cast run its course first. That can be done by using the <attribute>_before_type_cast accessors that all attributes have. For example, if your Account model has a balance attribute, you can call $Account->balance_before_type_cast or $Account->id_before_type_cast.
This is especially useful in validation situations where the user might supply a string for an integer field and you want to display the original string back in an error message. Accessing the attribute normally would type cast the string to 0, which isn't what you want.
== Saving arrays, hashes, and other non-mappable objects in text columns ==
Active Record can serialize any object in text columns. To do so, you must specify this with by setting the attribute serialize with a comma separated list of columns or an array. This makes it possible to store arrays, hashes, and other non-mappeable objects without doing any additional work. Example:
== Single table inheritance ==
Active Record allows inheritance by storing the name of the class in a column that by default is called "type" (can be changed by overwriting <tt>AkActiveRecord->_inheritanceColumn</tt>). This means that an inheritance looking like this:
When you do $Firm->create('name =>', "akelos"), this record will be saved in the companies table with type = "Firm". You can then fetch this row again using $Company->find('first', "name = '37signals'") and it will return a Firm object.
If you don't have a type column defined in your table, single-table inheritance won't be triggered. In that case, it'll work just like normal subclasses with no special magic for differentiating between them or reloading the right type with find.
Note, all the attributes for all the cases are kept in the same table. Read more: http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html
== Connection to multiple databases in different models ==
Connections are usually created through AkActiveRecord->establishConnection and retrieved by AkActiveRecord->connection. All classes inheriting from AkActiveRecord will use this connection. But you can also set a class-specific connection. For example, if $Course is a AkActiveRecord, but resides in a different database you can just say $Course->establishConnection and $Course and all its subclasses will use this connection instead.
Active Records will automatically record creation and/or update timestamps of database objects if fields of the names created_at/created_on or updated_at/updated_on are present. Date only: created_on, updated_on Date and time: created_at, updated_at
This behavior can be turned off by setting <tt>$this->_recordTimestamps = false</tt>.
Constructor __construct (line 257)
Overrides : AkObject::__construct() Class constructor, overriden in descendant classes
Destructor __destruct (line 313)
Overrides : AkObject::__destruct() Class destructor, overriden in descendant classes
Method actsAs (line 4471)
Example: $this->actsAs('list', array('scope' => 'todo_list'));
Method actsLike (line 4540)
Method addCombinedAttributeConfiguration (line 2154)
Method addConditions (line 1370)
Method addError (line 4271)
If no $message is supplied, "invalid" is assumed.
Method addErrorOnBlank (line 4294)
Method addErrorOnBoundaryBreaking (line 4309)
If the length is above the boundary, the too_long_message message will be used. If below, the too_short_message.
Method addErrorOnBoundryBreaking (line 4326)
Method addErrorOnEmpty (line 4280)
Method addErrorToBase (line 4250)
Method addObserver (line 4203)
Method attributesFromColumnDefinition (line 2518)
Method average (line 4885)
$Person->average('age');
Method beforeCreate (line 3411)
before or after an alteration of the object state. This can be used to make sure that associated and dependent objects are deleted when destroy is called (by overwriting beforeDestroy) or to massage attributes before they're validated (by overwriting beforeValidation). As an example of the callbacks initiated, consider the AkActiveRecord->save() call:
That's a total of 15 callbacks, which gives you immense power to react and prepare for each state in the Active Record lifecycle.
Examples: class CreditCard extends ActiveRecord { // Strip everything but digits, so the user can specify "555 234 34" or // "5552-3434" or both will mean "55523434" function beforeValidationOnCreate { if(!empty($this->number)){ $this->number = ereg_replace('[^0-9]*','',$this->number); } } }
class Subscription extends ActiveRecord { // Note: This is not implemented yet var $beforeCreate = 'recordSignup';
function recordSignup() { $this->signed_up_on = date("Y-m-d"); } }
class Firm extends ActiveRecord { //Destroys the associated clients and people when the firm is destroyed // Note: This is not implemented yet var $beforeDestroy = array('destroyAssociatedPeople', 'destroyAssociatedClients');
function destroyAssociatedPeople() { $Person = new Person(); $Person->destroyAll("firm_id=>", $this->id); }
function destroyAssociatedClients() { $Client = new Client(); $Client->destroyAll("client_of=>", $this->id); } }
== Canceling callbacks ==
If a before* callback returns false, all the later callbacks and the associated action are cancelled. If an after* callback returns false, all the later callbacks are cancelled. Callbacks are generally run in the order they are defined, with the exception of callbacks defined as methods on the model, which are called last.
Override this methods to hook Active Records
Method calculate (line 4947)
Options such as 'conditions', 'order', 'group', 'having', and 'joins' can be passed to customize the query.
There are two basic forms of output: * Single aggregate value: The single value is type cast to integer for COUNT, float for AVG, and the given column's type for everything else. * Grouped values: This returns an ordered hash of the values and groups them by the 'group' option. It takes a column name.
$values = $Person->maximum('age', array('group' => 'last_name')); echo $values["Drake"] => 43
Options: * <tt>'conditions'</tt>: An SQL fragment like "administrator = 1" or array( "user_name = ?", username ). See conditions in the intro. * <tt>'joins'</tt>: An SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id". (Rarely needed). The records will be returned read-only since they will have attributes that do not correspond to the table's columns. * <tt>'order'</tt>: An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations). * <tt>'group'</tt>: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause. * <tt>'select'</tt>: By default, this is * as in SELECT * FROM, but can be changed if you for example want to do a join. * <tt>'distinct'</tt>: Set this to true to make this a distinct calculation, such as SELECT COUNT(DISTINCT posts.id) ...
Examples: $Person->calculate('count', 'all'); // The same as $Person->count(); $Person->average('age'); // SELECT AVG(age) FROM people... $Person->minimum('age', array('conditions' => array('last_name != ?', 'Drake'))); // Selects the minimum age for everyone with a last name other than 'Drake' $Person->minimum('age', array('having' => 'min(age) > 17', 'group' => 'last'_name)); // Selects the minimum age for any family without any minors
Method castAttributeForDatabase (line 3151)
Method castAttributeFromDatabase (line 3215)
Method clearErrors (line 4421)
Method cloneRecord (line 343)
Method collect (line 4729)
$people_for_select = Ak::select($People->find(),'id','email');
Returns something like: array ( array ('10' => 'jose@example.com'), array ('15' => 'alicia@example.com'), array ('16' => 'hilario@example.com'), array ('18' => 'bermi@example.com') );
Method composeCombinedAttribute (line 2185)
Method constructFinderSql (line 1347)
Method count (line 4873)
* Count all: By not passing any parameters to count, it will return a count of all the rows for the model. * Count by conditions or joins * Count using options will find the row count matched by the options used.
The last approach, count using options, accepts an option hash as the only parameter. The options are:
* <tt>'conditions'</tt>: An SQL fragment like "administrator = 1" or array("user_name = ?", $username ). See conditions in the intro. * <tt>'joins'</tt>: An SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id". (Rarely needed). * <tt>'order'</tt>: An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations). * <tt>'group'</tt>: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause. * <tt>'select'</tt>: By default, this is * as in SELECT * FROM, but can be changed if you for example want to do a join. * <tt>'distinct'</tt>: Set this to true to make this a distinct calculation, such as SELECT COUNT(DISTINCT posts.id) ...
Examples for counting all: $Person->count(); // returns the total count of all people
Examples for count by +conditions+ and +joins+ (this has been deprecated): $Person->count("age > 26"); // returns the number of people older than 26 $Person->find("age > 26 AND job.salary > 60000", "LEFT JOIN jobs on jobs.person_id = ".$Person->id); // returns the total number of rows matching the conditions and joins fetched by SELECT COUNT(*).
Examples for count with options: $Person->count('conditions' => "age > 26"); $Person->count('conditions' => "age > 26 AND job.salary > 60000", 'joins' => "LEFT JOIN jobs on jobs.person_id = $Person->id"); // finds the number of rows matching the conditions and joins. $Person->count('id', 'conditions' => "age > 26"); // Performs a COUNT(id) $Person->count('all', 'conditions' => "age > 26"); // Performs a COUNT(*) ('all' is an alias for '*')
Note: $Person->count('all') will not work because it will use 'all' as the condition. Use $Person->count() instead.
Method countBySql (line 578)
$Product->countBySql("SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id");
Method countErrors (line 4430)
Method create (line 393)
Overrides : AkAssociatedActiveRecord::create() parent method not documented
If the save fail under validations, the unsaved object is still returned.
Method createOrUpdate (line 410)
Method dbugging (line 4599)
Method debug (line 4610)
Method decomposeCombinedAttribute (line 2260)
Method decrementAndSaveAttribute (line 1854)
Method decrementAttribute (line 1843)
Method decrementCounter (line 1835)
Method delete (line 723)
Method deleteAll (line 742)
Important note: Conditions are not sanitized yet so beware of accepting variable conditions when using this function
Method descendsFromActiveRecord (line 1522)
Method destroy (line 762)
Deletes the record in the database and freezes this instance to reflect that no changes should be made (since they can't be persisted).
Method destroyAll (line 822)
Example:
$Person->destroyAll("last_login < '2004-04-04'");
Method establishConnection (line 2342)
$AkActiveRecord->establishConnection('development'); $AkActiveRecord->establishConnection('super_user');
$AkActiveRecord->establishConnection( array( 'type' => "mysql", 'host' => "localhost", 'username' => "myuser", 'password' => "mypass", 'database' => "somedatabase" ));
Example for SQLite database:
$AkActiveRecord->establishConnection( array( 'type' => "sqlite", 'dbfile' => "path/to/dbfile" ) )
Method exists (line 853)
$Person->exists(5);
Method find (line 903)
Overrides : AkAssociatedActiveRecord::find() parent method not documented
* Find first: This will return the first record matched by the options used. These options can either be specific conditions or merely an order. If no record can matched, false is returned. * Find all: This will return all the records matched by the options used. If no records are found, an empty array is returned.
All approaches accepts an $option array as their last parameter. The options are:
'conditions' => An SQL fragment like "administrator = 1" or array("user_name = ?" => $username). See conditions in the intro. 'order' => An SQL fragment like "created_at DESC, name". 'limit' => An integer determining the limit on the number of rows that should be returned. 'offset' => An integer determining the offset from where the rows should be fetched. So at 5, it would skip the first 4 rows. 'joins' => An SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = $id". (Rarely needed). 'include' => Names associations that should be loaded alongside using LEFT OUTER JOINs. The symbols named refer to already defined associations. See eager loading under Associations.
Examples for find by id:
Examples for find first:
Examples for find all:
Method findBy (line 1197)
findBy('username AND password', $username, $password); findBy('age > ? AND name:contains', 18, 'Joe'); findBy('is_active = true AND session_id', session_id());
Method findBySql (line 1133)
$Post->findBySql("SELECT p.*, c.author FROM posts p, comments c WHERE p.id = c.post_id"); $Post->findBySql(array("SELECT * FROM posts WHERE author = ? AND created_on > ?", $author_id, $start_date));
Method findFirstBy (line 1154)
Method freeze (line 5127)
Method get (line 1740)
Method getAkelosDataType (line 2814)
Returns the Akelos data type for an Adodb Column Object
'C'=>'string', // Varchar, capped to 255 characters. 'X' => 'text' // Larger varchar, capped to 4000 characters (to be compatible with Oracle). 'XL' => 'text' // For Oracle, returns CLOB, otherwise the largest varchar size.
'C2' => 'string', // Multibyte varchar 'X2' => 'string', // Multibyte varchar (largest size)
'B' => 'binary', // BLOB (binary large object)
'D' => array('date', 'datetime'), // Date (some databases do not support this, and we return a datetime type) 'T' => array('datetime', 'timestamp'), //Datetime or Timestamp 'L' => 'boolean', // Integer field suitable for storing booleans (0 or 1) 'I' => // Integer (mapped to I4) 'I1' => 'integer', // 1-byte integer 'I2' => 'integer', // 2-byte integer 'I4' => 'integer', // 4-byte integer 'I8' => 'integer', // 8-byte integer 'F' => 'float', // Floating point number 'N' => 'integer' // Numeric or decimal number
Method getArrayFromAkString (line 4809)
Acts like Php explode() function but uses any of this as valid separators ' AND ',' and ',' + ',' ',',',';'
Method getAttribute (line 1698)
Method getAttributeBeforeTypeCast (line 3099)
Method getAttributeByLocale (line 2989)
Method getAttributeCaption (line 1969)
Method getAttributeCondition (line 4820)
Method getAttributeLocales (line 2997)
Method getAttributeNames (line 2027)
Method getAttributes (line 1748)
Method getAttributesQuoted (line 3128)
Method getBaseErrors (line 4258)
Method getClassForDatabaseTableMapping (line 2888)
Method getColumns (line 2589)
Method getColumnSettings (line 2598)
Method getColumnsForAttributes (line 2474)
Method getCombinedSubattributes (line 2235)
Method getConditions (line 1406)
Method getConnection (line 2361)
Method getContentColumns (line 2011)
Method getErrors (line 4239)
Method getErrorsOn (line 4344)
Returns the error message, if one error is associated with the specified $attribute. Returns an array of error messages, if more than one error is associated with the specified $attribute.
Method getFullErrorMessages (line 4394)
Method getId (line 1773)
Overrides : AkAssociatedActiveRecord::getId() parent method not documented
Method getInheritanceColumn (line 1537)
Method getObservers (line 4218)
Method getOnlyAvailableAttributes (line 2455)
Method getSanitizedConditionsArray (line 1389)
Method getSerializedAttributes (line 1959)
Method getTableName (line 2406)
Method getType (line 5140)
Overrides : AkAssociatedActiveRecord::getType() parent method not documented
Method hasAttribute (line 2054)
Method hasAttributesDefined (line 1977)
Method hasColumn (line 2496)
Method incrementAndSaveAttribute (line 1874)
Method incrementAttribute (line 1863)
Method incrementCounter (line 1827)
$discussion_board_id); would increment the "post_count" counter on the board responding to $discussion_board_id. This is used for caching aggregate values, so that they doesn't need to be computed every time. Especially important for looping over a collection where each element require a number of aggregate values. Like the $DiscussionBoard that needs to list both the number of posts and comments.
Method initiateAttributeToNull (line 2771)
Method instantiate (line 1488)
that makes it possible to create objects of different types from the same table.
Method isAttributePresent (line 2042)
Method isCombinedAttribute (line 2149)
Method isConnected (line 2352)
Method isInvalid (line 4334)
Method isLockingEnabled (line 3318)
$p1 = new Person(1); $p2 = new Person(1);
$p1->first_name = "Michael"; $p1->save();
$p2->first_name = "should fail"; $p2->save(); // Returns false
You're then responsible for dealing with the conflict by checking the return value of save(); and either rolling back, merging, or otherwise apply the business logic needed to resolve the conflict.
You must ensure that your database schema defaults the lock_version column to 0.
This behavior can be turned off by setting <tt>AkActiveRecord::lock_optimistically = false</tt>.
Method isNewRecord (line 357)
Method isValid (line 4023)
Method loadColumnsSettings (line 2607)
Method maximum (line 4905)
$Person->maximum('age');
Method minimum (line 4895)
$Person->minimum('age');
Method newRecord (line 324)
In both instances, valid attribute keys are determined by the column names of the associated table; hence you can't have attributes that aren't part of the table columns.
Method notifyObservers (line 4162)
Method parseAkelosArgs (line 4777)
This function generates an array with values and keys from an array with numeric keys.
This allows to parse an array to a function in the following manner. create('first_name->', 'Bermi', 'last_name->', 'Ferrer'); //Previous code will be the same that create(array('first_name'=>'Bermi', 'last_name'=> 'Ferrer'));
Use this syntax only for quick testings, not for production environments. If the number of arguments varies, the result might be unpredictable.
This function syntax is disabled by default. You need to define('AK_ENABLE_AKELOS_ARGS', true) if you need this functionality.
Method reload (line 370)
Method removeAttributesProtectedFromMassAssignment (line 1930)
Method requiredForCombination (line 2220)
Method resetColumnInformation (line 2681)
Method save (line 537)
Method select (line 4697)
$people_for_select = $People->select($People->find(),'name','email');
Now $people_for_select will hold an array with array ( array ('name' => 'Jose','email' => 'jose@example.com'), array ('name' => 'Alicia','email' => 'alicia@example.com'), array ('name' => 'Hilario','email' => 'hilario@example.com'), array ('name' => 'Bermi','email' => 'bermi@example.com') );
Method set (line 1649)
Method setAccessibleAttributes (line 1893)
This is the more conservative choice for mass-assignment protection. If you'd rather start from an all-open default and restrict attributes as needed, have a look at AkActiveRecord::setProtectedAttributes().
Method setAttribute (line 1600)
Method setAttributeByLocale (line 3008)
Method setAttributeLocales (line 3018)
Method setAttributes (line 1665)
Sensitive attributes can be protected from this form of mass-assignment by using the $this->setProtectedAttributes method. Or you can alternatively specify which attributes can be accessed in with the $this->setAccessibleAttributes method. Then all the attributes not included in that won?t be allowed to be mass-assigned.
Method setColumnSettings (line 2643)
Method setConnection (line 2369)
Method setDisplayField (line 2914)
Method setInheritanceColumn (line 1545)
Method setObservableState (line 4189)
Method setPrimaryKey (line 2396)
Method setProtectedAttributes (line 1924)
This is meant to protect sensitive attributes to be overwritten by URL/form hackers.
Example:
Method setSerializeAttribute (line 3115)
Method setTableName (line 2423)
Method sum (line 4915)
$Person->sum('age');
Method toggleAttribute (line 1790)
Method toggleAttributeAndSave (line 1802)
Method toString (line 4568)
Overrides : AkObject::toString() Object-to-string conversion
Method toYaml (line 4754)
examples: User::toYaml($users->find('all')); $Bermi->toYaml();
Method transactionStart (line 3449)
Transactions are enabled automatically for Active record objects, But you can nest transactions within models. This transactions are nested, and only the outermost will be executed
$User->transactionStart(); $User->create('username'=>'Bermi'); $Members->create('username'=>'Bermi');
if(!checkSomething()){ $User->transactionFail(); }
$User->transactionComplete();
Method typeCondition (line 1579)
Method update (line 604)
Method updateAll (line 651)
Important note: Conditions are not sanitized yet so beware of accepting variable conditions when using this function
Method updateAttribute (line 625)
Method updateAttributes (line 636)
Method validate (line 4111)
Method validateOnCreate (line 4118)
Method validateOnUpdate (line 4125)
Method validatesAcceptanceOf (line 3579)
class Person extends ActiveRecord { function validateOnCreate() { $this->validatesAcceptanceOf('terms_of_service'); $this->validatesAcceptanceOf('eula', "must be abided"); } }
The terms_of_service attribute is entirely virtual. No database column is needed. This check is performed only if terms_of_service is not null.
Method validatesAssociated (line 3620)
class Book extends ActiveRecord { var $has_many = 'pages'; var $belongs_to = 'library';
function validate(){ $this->validatesAssociated(array('pages', 'library')); } }
Warning: If, after the above definition, you then wrote:
class Page extends ActiveRecord { var $belongs_to = 'book'; function validate(){ $this->validatesAssociated('book'); } }
...this would specify a circular dependency and cause infinite recursion.
NOTE: This validation will not fail if the association hasn't been assigned. If you want to ensure that the association is both present and guaranteed to be valid, you also need to use validatesPresenceOf.
Method validatesConfirmationOf (line 3548)
Model: class Person extends ActiveRecord { function validate() { $this->validatesConfirmationOf('password'); $this->validatesConfirmationOf('email_address', "should match confirmation"); } }
View: <?=$form_helper->password_field("person", "password"); ?> <?=$form_helper->password_field("person", "password_confirmation"); ?>
The person has to already have a password attribute (a column in the people table), but the password_confirmation is virtual. It exists only as an in-memory variable for validating the password. This check is performed only if password_confirmation is not null.
Method validatesExclusionOf (line 3957)
class Person extends ActiveRecord { function validate() { $this->validatesExclusionOf('username', array('admin', 'superuser'), "You don't belong here"); $this->validatesExclusionOf('age', range(30,60), "This site is only for under 30 and over 60"); } }
Parameters: <tt>$array_of_possibilities</tt> - An array of items that the value shouldn't be part of <tt>$message</tt> - Specifies a customer error message (default is: "is reserved") <tt>$allow_null</tt> - If set to true, skips this validation if the attribute is null (default is: false)
Method validatesFormatOf (line 3900)
A regular expression must be provided or else an exception will be raised.
There are some regular expressions bundled with the Akelos Framework. You can override them by defining them as PHP constants (Ie. define('AK_EMAIL_REGULAR_EXPRESSION', '/^My custom email regex$/');). This must be done on your main configuration file. This are predefined perl-like regular extensions.
* AK_NOT_EMPTY_REGULAR_EXPRESSION ---> /.+/ * AK_EMAIL_REGULAR_EXPRESSION ---> /^([a-z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-z0-9\-]+\.)+))([a-z]{2,4}|[0-9]{1,3})(\]?)$/i * AK_NUMBER_REGULAR_EXPRESSION ---> /^[0-9]+$/ * AK_PHONE_REGULAR_EXPRESSION ---> /^([\+]?[(]?[\+]?[ ]?[0-9]{2,3}[)]?[ ]?)?[0-9 ()\-]{4,25}$/ * AK_DATE_REGULAR_EXPRESSION ---> /^(([0-9]{1,2}(\-|\/|\.| )[0-9]{1,2}(\-|\/|\.| )[0-9]{2,4})|([0-9]{2,4}(\-|\/|\.| )[0-9]{1,2}(\-|\/|\.| )[0-9]{1,2})){1}$/ * AK_IP4_REGULAR_EXPRESSION ---> /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/ * AK_POST_CODE_REGULAR_EXPRESSION ---> /^[0-9A-Za-z -]{2,7}$/
IMPORTANT: Predefined regular expressions may change in newer versions of the Framework, so is highly recommended to hardcode you own on regex on your validators.
Params: <tt>$message</tt> - A custom error message (default is: "is invalid") <tt>$regular_expression</tt> - The regular expression used to validate the format with (note: must be supplied!)
Method validatesInclusionOf (line 3928)
class Person extends ActiveRecord { function validate() { $this->validatesInclusionOf('gender', array('male', 'female'), "woah! what are you then!??!!"); $this->validatesInclusionOf('age', range(0, 99)); }
Parameters: <tt>$array_of_ possibilities</tt> - An array of available items <tt>$message</tt> - Specifies a customer error message (default is: "is not included in the list") <tt>$allow_null</tt> - If set to true, skips this validation if the attribute is null (default is: false)
Method validatesLengthOf (line 3688)
class Person extends ActiveRecord { function validate() { $this->validatesLengthOf('first_name', array('maximum'=>30)); $this->validatesLengthOf('last_name', array('maximum'=>30,'message'=> "less than %d if you don't mind")); $this->validatesLengthOf('last_name', array('within'=>array(7, 32))); $this->validatesLengthOf('last_name', array('in'=>array(6, 20), 'too_long' => "pick a shorter name", 'too_short' => "pick a longer name")); $this->validatesLengthOf('fav_bra_size', array('minimum'=>1, 'too_short'=>"please enter at least %d character")); $this->validatesLengthOf('smurf_leader', array('is'=>4, 'message'=>"papa is spelled with %d characters... don't play me.")); } }
NOTE: Be aware that $this->validatesLengthOf('field', array('is'=>5)); Will match a string containing 5 characters (Ie. "Spain"), an integer 5, and an array with 5 elements. You must supply additional checking to check for appropriate types.
Configuration options: <tt>minimum</tt> - The minimum size of the attribute <tt>maximum</tt> - The maximum size of the attribute <tt>is</tt> - The exact size of the attribute <tt>within</tt> - A range specifying the minimum and maximum size of the attribute <tt>in</tt> - A synonym(or alias) for :within <tt>allow_null</tt> - Attribute may be null; skip validation.
<tt>too_long</tt> - The error message if the attribute goes over the maximum (default "is" "is too long (max is %d characters)") <tt>too_short</tt> - The error message if the attribute goes under the minimum (default "is" "is too short (min is %d characters)") <tt>wrong_length</tt> - The error message if using the "is" method and the attribute is the wrong size (default "is" "is the wrong length (should be %d characters)") <tt>message</tt> - The error message to use for a "minimum", "maximum", or "is" violation. An alias of the appropriate too_long/too_short/wrong_length message
Method validatesNumericalityOf (line 3989)
class Person extends ActiveRecord { function validate() { $this->validatesNumericalityOf('value'); } }
Parameters: <tt>$message</tt> - A custom error message (default is: "is not a number") <tt>$only_integer</tt> Specifies whether the value has to be an integer, e.g. an integral value (default is false) <tt>$allow_null</tt> Skip validation if attribute is null (default is false).
Method validatesPresenceOf (line 3647)
Method validatesSizeOf (line 3771)
Method validatesUniquenessOf (line 3813)
class Person extends ActiveRecord { function validate() { $this->validatesUniquenessOf('passport_number'); $this->validatesUniquenessOf('user_name', array('scope' => "account_id")); } }
It can also validate whether the value of the specified attributes are unique based on multiple scope parameters. For example, making sure that a teacher can only be on the schedule once per semester for a particular class.
class TeacherSchedule extends ActiveRecord { function validate() { $this->validatesUniquenessOf('passport_number'); $this->validatesUniquenessOf('teacher_id', array('scope' => array("semester_id", "class_id")); } }
When the record is created, a check is performed to make sure that no record exist in the database with the given value for the specified attribute (that maps to a column). When the record is updated, the same check is made but disregarding the record itself.
Configuration options: <tt>message</tt> - Specifies a custom error message (default is: "has already been taken") <tt>scope</tt> - Ensures that the uniqueness is restricted to a condition of "scope = record.scope" <tt>case_sensitive</tt> - Looks for an exact match. Ignored by non-text columns (true by default). <tt>if</tt> - Specifies a method to call or a string to evaluate to determine if the validation should occur (e.g. 'if' => 'allowValidation', or 'if' => '$this->signup_step > 2'). The method, or string should return or evaluate to a true or false value.
Method yieldEachError (line 4360)
Method yieldEachFullError (line 4382)
Method _extractConditionsFromArgs (line 1042)
Method _extractOptionsFromArgs (line 1022)
Method _extractValueFromDefault (line 5167)
Method _getFindBySqlAndColumns (line 1256)
Method _getVariableSqlCondition (line 1334)
Method _sanitizeConditionsVariables (line 1079)
Method _validateFindOptions (line 1099)
AkAssociatedActiveRecord::$_AssociationHandler -
AkAssociatedActiveRecord::$_associationId -
AkAssociatedActiveRecord::$_associationIds -
AkBaseModel::$_modelName -
AkAssociatedActiveRecord::assign() -
AkAssociatedActiveRecord::build() - Returns a new object of the associated type that has been instantiated with attributes and linked to this object through a foreign key but has not yet been saved.
AkAssociatedActiveRecord::constructFinderSqlWithAssociations() - Used for generating custom selections for habtm, has_many and has_one queries
AkAssociatedActiveRecord::constructSql() -
AkAssociatedActiveRecord::constructSqlForInclusion() -
AkAssociatedActiveRecord::create() -
AkAssociatedActiveRecord::find() -
AkAssociatedActiveRecord::findWithAssociations() -
AkAssociatedActiveRecord::getAssociated() - Gets an array of associated object of selected association type.
AkAssociatedActiveRecord::getAssociatedFinderSqlOptions() -
AkAssociatedActiveRecord::getAssociatedHandlerName() -
AkAssociatedActiveRecord::getAssociatedIds() -
AkAssociatedActiveRecord::getAssociatedType() -
AkAssociatedActiveRecord::getAssociationId() -
AkAssociatedActiveRecord::getAssociationOption() -
AkAssociatedActiveRecord::getAssociationType() -
AkAssociatedActiveRecord::getCollectionHandlerName() -
AkAssociatedActiveRecord::getId() -
AkAssociatedActiveRecord::getType() -
AkAssociatedActiveRecord::hasAssociations() -
AkAssociatedActiveRecord::load() -
AkAssociatedActiveRecord::loadAssociations() -
AkAssociatedActiveRecord::replace() -
AkAssociatedActiveRecord::setAssociationHandler() -
AkAssociatedActiveRecord::setAssociationOption() -
AkAssociatedActiveRecord::_addTableAliasesToAssociatedSql() -
AkAssociatedActiveRecord::_findBySqlWithAssociations() -
AkAssociatedActiveRecord::_loadAssociationHandler() -
AkBaseModel::getModelName() - Returns current model name
AkBaseModel::getParentModelName() -
AkBaseModel::setModelName() - Sets current model name
AkBaseModel::setParentModelName() -
AkBaseModel::_getIncludedModelNames() -
AkBaseModel::_getModelName() - This method will nicely handle model names even on
AkObject::AkObject() - A hack to support __construct() on PHP 4
AkObject::__construct() - Class constructor, overriden in descendant classes
AkObject::freeMemory() - Unsets circular reference children that are not freed from memory when calling unset() or when the parent object is garbage collected.
AkObject::log() -
AkObject::toString() - Object-to-string conversion
AkObject::__clone() - Clone class (Zend Engine 2 compatibility trick)
AkObject::__destruct() - Class destructor, overriden in descendant classes
AkObject::__toString() -