close
Phork Manual Table of Contents
Phork Framework User Guide 1.3.4

CoreDatabaseModel

Filepath: phork/php/core/CoreDatabaseModel.class.php
Version: 1.3 and higher

The CoreDatabaseModel class is an abstract class that's an extension of the CoreModel class. It's used to load, add, edit and delete data stored in a database.

A very basic extension of this class will define the table name and primary key of the database table as well as the names of the columns to insert and update when adding and editing a record. More advanced extensions can take advantage of things like helpers and custom queries with table joins.


Basic Model

require_once('php/core/CoreDatabaseModel.class.php');

class UserModel extends CoreDatabaseModel {

    //the database table and primary key
    protected $strTable = 'users';
    protected $strPrimaryKey = 'userid';
    
    //the column names to save on insert and update
    protected $arrInsertCols = array('username', 'password', 'email', 'birthdate', 'created', 'updated');
    protected $arrUpdateCols = array('password', 'email', 'birthdate', 'updated');
}

Advanced Model with Helpers

require_once('php/core/CoreDatabaseModel.class.php');

class UserModel extends CoreDatabaseModel {

    //set up the user record class to hold each record
    protected $strRecordClass = 'UserRecord';
    
    //the database table and primary key
    protected $strTable = 'users';
    protected $strPrimaryKey = 'userid';
    
    //the column names to save on insert and update
    protected $arrInsertCols = array('username', 'password', 'email', 'birthdate', 'created', 'updated');
    protected $arrUpdateCols = array('password', 'email', 'birthdate', 'updated');
    
    
    /**
     * Includes the record class, sets up an iterator 
     * object to hold the records, and sets up an event 
     * key which is used to register and run events in
     * the event object. This also sets up the relations
     * helper to load relations and the validation helper.
     *
     * @access public
     * @param array $arrConfig The config vars, including which helpers to use
     */
    public function __construct($arrConfig = array()) {
        parent::__construct($arrConfig);
        
        //register the event to call setDefaults() to set any default values before saving
        AppEvent::register($this->strEventKey . '.pre-save', array($this, 'setDefaults'));
        
        //if the validation flag was passed in the config set up the validation helper
        if (!empty($arrConfig['Validate'])) {
            if (AppLoader::includeExtension('helpers/', 'ModelValidation')) {
                $this->appendHelper('validation', 'ModelValidation', array(
                    'Id'              => array(
                        'Property'        => 'userid',
                        'Unique'          => true,
                        'Type'            => 'integer',
                        'Error'           => 'Invalid ID'
                    ),
                    
                    'Username'        => array(
                        'Property'       => 'username',
                        'Unique'         => true,
                        'Required'       => true,
                        'Type'           => 'string',
                        'RegEx'          => '/^[0-9a-z]{3,20}$/i',
                        'Error'          => 'Invalid username. It must be between 3 and 20 characters in length, containing only a-z and 0-9.',
                    ),
            
                    'Password'        => array(
                        'Property'       => 'password',
                        'Required'       => true,
                        'Type'           => 'string',
                        'Error'          => 'Invalid password'
                    ),
                    
                    'Email'           => array(
                        'Property'       => 'email',
                        'Unique'         => true,
                        'Required'       => true,
                        'Type'           => 'email',
                        'CheckMx'        => false,
                        'Error'          => 'Invalid email address'
                    ),
                    
                    'Birthdate'       => array(
                        'Property'       => 'birthdate',
                        'Required'       => true,
                        'Type'           => 'string',
                        'RegEx'          => '/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/',
                        'Error'          => 'Invalid birthdate'
                    )
                ));
                
                //initialize the validation helper
                $this->initHelper('validation', array('validateAll'));
            }
        }
        
        //if the relations flag was passed in the config set up the relations helper
        if (!empty($arrConfig['Relations'])) {
            if (AppLoader::includeExtension('helpers/', 'ModelRelations')) {
                $this->appendHelper('relations', 'ModelRelations', array(
                
                    //the options here are HasMany, HasOne, BelongsToMany and BelongsToOne
                    'HasMany'         => array(
                        'Blogs'          => array(
                            'LoadAs'        => 'blogs',
                            'AutoLoad'      => false,
                            'ClassName'     => 'BlogModel',
                            'Dependent'     => true,
                            'Conditions'    => array(
                                array(
                                    'Column'      => 'userid',
                                    'Property'    => $this->strPrimaryKey,
                                    'Operator'    => '='
                                )
                            ),
                            'Order'         => array(
                                array(
                                    'Column'      => 'published',
                                    'Sort'        => 'desc'
                                )
                            ),
                            'Config'        => array(
                                'NoUserJoin'      => true
                            )
                        ),
                    )
                ));
                
                //initialize the relations if the auto load flag was set in the config, also set up the optional recursion level
                if (!empty($arrConfig['RelationsAutoLoad'])) {
                    $this->initHelper('relations', array('loadAutoLoad'), array(
                        'Recursion' => isset($arrConfig['RelationsRecursion']) ? $arrConfig['RelationsRecursion'] : 0
                    ));
                }
            }
        }
    }
    
    
    /**
     * Sets the created and updated values before saving
     * the record.
     *
     * @access public
     */
    public function setDefaults() {
        $objDb = AppRegistry::get('Database');
        if (!$this->current()->get('__id')) {
            $this->current()->set('created', date($objDb->getDatetimeFormat()));
        }
        $this->current()->set('updated', date($objDb->getDatetimeFormat()));
    }


    /**
     * A shortcut function to load a record by username.
     * This does not clear out any previously loaded data.
     * That should be done explicitly.
     *
     * @access public
     * @param string $strUsername The username to load by
     * @return boolean True if the query executed successfully
     */
    public function loadByUsername($strUsername) {
        $arrFunctionArgs = func_get_args();
        $this->setLoading(__FUNCTION__, $arrFunctionArgs);
        
        $blnResult = $this->load(array(
            'Conditions' => array(
                array(
                    'Column' => 'username',
                    'Value'  => $strUsername
                )
            )        
        ));
        
        $this->clearLoading();
        return $blnResult;
    }
}

Basic Loading

if (AppLoader::includeMode('UserModel')) {

    //set up the objects to load all the autoload relations
    $objUser = new UserModel(array(
        'Relations'          => true,
        'RelationsAutoLoad'  => true
    ));
    
    //load a single user with the autoload relations
    if ($objUser->loadById(1)) {
    
        //get the entire record object
        $objRecord = $objUser->getRecords()->first();
        
        //get just the username from the record object
        $strUsername = $objUser->getRecords()->first()->getUsername();
    }
    
    //clear out the loaded user
    $objUser->clear();
    
    
    //set up the params to load the 31st to 40th users to sign up
    $arrParams = array(
        'Order'    => array(
            array(
                'Column'   => 'created',
                'Sort'     => 'ASC'
            )
        ),
        'Limit'    => 10,
        'Offset'   => 30
    );

    //load the users and their relations
    if ($objUser->load($arrParams)) {
        print $objUser->getFoundRows() . ' users found<br />';
        print $objUser->count() . ' users loaded';
    }
    
    //print each username
    while (list(, $objRecord) = $objUser->each()) {
        print $objRecord->get('username') . '<br />';
    }
}

Basic Saving

if (AppLoader::includeMode('UserModel')) {
    $objUser = new UserModel();
    
    //import data into the user model
    $objUser->import(array(
        'username'           => 'foo',
        'password_plaintext' => 'bar',
        'email'              => 'foo@example.com',
        'birthdate'          => '1979-01-01'
    ));
    
    //save the record
    $blnResult = $objUser->save();
}

Specific Relations

//set up the relations in the user model but don't set up the autoloader
$objUser = new UserModel(array(
    'Relations' => true
));

//set up the object to load the users roles and their blogs
$objUser->initHelper('relations', array('loadSpecific'), array(
    'Relations' => array('HasMany.Role', 'HasMany.Blogs')
));

//load the user with the relationships
if ($objUser->loadById(1) && $objUser->loadById(1)->first()) {
    //do something here
}

Cache Helper

//set up the cache helper to attempt to load the data from the cache and to recache on failure
AppLoader::includeExtension('helpers/', 'ModelCache');
$objUser->appendHelper('cache', 'ModelCache');
$objUser->initHelper('cache', array('preLoad', 'postLoad'), array('Namespace' => 'test', 'Expire' => 60));

if ($objUser->load(array('Limit' => 2), true)) {
    while (list(, $objRecord) = $objUser->each()) {
        print 'username = ' . $objRecord->get('username') . '<br />';
    }
}

//destroy the cache helper otherwise it will be applied to subsequent object loads
$objUser->destroyHelper('cache');