Skip to content
stanistan edited this page Jul 25, 2011 · 8 revisions

Start by defining your $sky_aql_model_path in config.php, you can start using the model system.

Assuming $sky_aql_model_path = 'models/';

Structure

In the models directory, you need a folder with the model name, we'll use 'artist.' In the artist folder, should be:

artist.aql

artist {
	name,
	bio
}

class.artist.php

class artist extends model {

}

Reserved Properties

  • _aql - stores actual .aql file when it is found in the models directory or the input aql
  • _aql_array - array generated by _aql
  • _data - all stored data, corresponds to properties and what they represent
  • _do_set - can be set prior to loadDB, will make sure object's data does not pull from cache
  • _errors - errors array
  • _id - the identifier, (if set) during loadDB
  • _ignore - _ignore array
  • _model_name - set by the class name
  • _objects - an array of objects (also in the properties array, also as keys), distinguishing between plural and singular objects
  • _primary_table - the primary table of the model, to which the _id applies
  • _properties - an array of properties (as keys in the array) can be fetched with model::getProperties
  • _required_fields - an array of required fields to be checked before save, in 'field_name' => 'Field' pairs
  • _return - information to add to the return array (after_save, after_fail)

Available Methods

AddProperty

Example:

class artist extends model {
    public function construct() {
        $this->addProperty('free_show', 'animals', 'coding', 'abc', 'def');
    }
}

$o = new artist;
$o->free_show = 'free';
$o->animals = 1;

Parameters:

(string) Property name to add (string) (optional) You can add many properties this way.

Return:

(model) So you can chain methods.

Note:

You cannot save the properties to the DB, this just makes it easier to interact with information.

AddSubModel

One can dynamically add to the model and have the results be saved as this is based on AQL and will add to the AQL array of the model. It differs from addProperty because addProprety just allows this information to be get/set in the object, but not in the database.

Example:

<?php
// Model for artist
// artist {
//     name
// }
//

class artist extends model {
	public function construct() {
                global $display_id;
		$args = array(
			'property' => 'artist_album',
			'aql' => "artist_album { artist_id, name } ",
			'clause' => array(
				'where' => "artist_id = {$this->_id} and display_id = {$display_id"
			)
		);
		$this->addSubModel($args);
	}
}

after_fail

###This function is called when you use the save method and the transaction fails.

Parameters:

(array) The save_array will be passed to the function

Return:

(array) The standard response array for model::save

after_save

Parameters:

(array) The save_array

Return:

(array) The standard response array for model::save

before_save

model::before_save is executed once the save transaction starts. You can change save_array in this function or trigger transaction failure. You must return the save array

Parameters:

(array) The save_array

Return:

(array) The save_array

construct

This is a function that executes automatically after the __construct method of a model.


class artist extends model {
    public function construct() {
         if ($this->_id) { // if the object is loaded
             $this->addProperty('fans')->loadFans();
             print_pre($this->fans);
         }
    }

    public function loadFans() {
        // some fan loading logic here
        $this->fans = aql::select($some_query);
    }
}

Paramters:

none

Returns:

(null)

dataToArray

The function returns a nested array of the object data, which is stored in $o->_data, since this can have sub objects, as defined by the model.

delete

Deletes the current object's record (sets active = 0) and returns the response array (status, data, errors)

failTransaction

Triggers a database transaction failure (useful for testing), should be called in model::before_save

get

Returns a model object, it checks to see if the class for the specified model exists and returns that, or returns a generic model object. The difference being the generic model object would have none of the specific methods that could be added/overwritten by making an artist class.

Example:

$o = model::get('artist', $id);
// equivalent to
// $o = new artist($id);
// or
// $o = new model($id, 'artist');
// if class artist does not exist

getIDByRequiredFields

Use this if you want to keep data records unique. You must model::$_required_fields for this to work.

Example:

<?php
    class song_review {
        public $_required_fields = array(
            'song_id' => 'Song',
            'reviewer_id' => 'Reviewer'
        );
        public function validate() {
             parent::validate();
             $this->getIDByRequiredFields();
        }
    }


?>

When saving the object, validation will set the song_review_id if it is not set, so duplicate/redundant data is not created.

loadArray

Parameters:

(array) Parses an array based on the AQL used to define it and populates _data array.

Returns:

(model) so you can chain methods.

$o = new artist();
$response = $o->loadArray($array)->save();

loadDB

Parameters:

  • (string) identifier, the ID or IDE of the record in the database.
  • (bool) defaults false. If this is set to true, it will not fetch the object from cache (if cache is enabled), but will use aql::profile and populate the cache

Returns:

(model) so you can chain methods.

$o =  new artist();
$response = $o->loadDB(10)->delete();

loadJSON

Decodes JSON to an array and uses loadArray();

Parameters:

(string) JSON string.

Returns:

(model)

reload

Used after save to refresh the object's data with the current information in the database. This will set the cache.

preFetchRequiredFields

Parameters:

($int) identifier Use this during validation to get required field data if it has not been submitted.

preValidate

A hook that can be defined in any object class that will run before model::validate()

returnJSON

returns a JSON string

Parameters:

  • (array)

Returns:

(string)

removeProperty

Usage is the same as addProperty

requiredField

used during validation, if the $val is empty, an error is added to the _errors array.

Parameters:

  • (string) Name of field, to be used in the error if the value is empty
  • (string) Value of field

Returns:

(bool) true if value exists

class artist extends model {
    set_name($val) {
        return $this->requiredField('Artist Name', $val);
    }
}

save

Example:

$o = new artist();
$o->loadArray(array(
	'name' => $name,
	'bio' => $bio
));
$response = $o->save();

Return:

(array) If the save fails, results of the function model::after_fail are returned, otherwise, model::after_save

Both of these can be overridden in the artist class but are already defined.

array(
	'status' => $status,
	'data' => $data,
	'errors' => $errors
)

Where $status is either OK or Error.

If $status != 'OK', it is expected that $errors = $this->_errors,

else $data = $this->_data or $data = $this->dataToArray()

validate

Is automatically run during model::save().

It looks for methods that look like set_field_name($val) after checking _required_fields array for field_name.

$_ignore

If you want to add information to the model, but make sure that it can never be overridden on a call to model::save() use the $_ignore array to set which parts of the model you want to omit from the save. This gets executed right before before_save()

Example:

Artist AQL:

artist {
    name,
    [artist_album]s
}
artist_type on artist.artist_type_id = artist_type.id {
   name as type
}

Artist Class:

class artist extends model {
    
    public $_ignore = array(
        'objects' => array('artist_album'),
        'tables' => array('artist_type')
        // 'subs' => array('artist_album') if "artist_album" was a subquery instead of a group of objects
    );

}

When $artist->save() is called, table artist_type, and subquery/model artist_album will be removed from the save_array.