Models

In PIP models are classes whose sole responsiblity it is to deal with data (usually from a database).

The PIP Model class provides basic functions (insert, update and delete) to maintain the database (see Database. It also has functions for validation (also see Helpers - Validation).

Using Models

Models are stored in the app/models folder:

Calls to the database can retreive records as objects, so the model should contain a set of public variables with the same names as the table columns.

The model should also contain protected variables for table-name and timestamp, and a function asArray() which are used by the Db (database) class to insert and update records - (see Database for more information).

<?php app/models/album.php
class Album extends Model {
    // fields
    public $id;
    public $title;
    public $year;
    public $artist_id;

    // table info
    protected $table = "albums";
    protected $timestamp = false;

    // return data as array
    public function asArray()
    {
        // make array of fields
        $array = [ 'id'    =>$this->id,
                   'title' => $this->title,
                   'year'  => $this->year,
                   'artist_id' => $this->artist_id
                 ];
        return $array;
    }

}
?>

If $timestamp is true then created_at and updated_at will be updated with the current time when records are created and updated. There is no need to include these fields in the asArray() function.

Database functions

Having defined the public fields (using column names), the table-name, timestamp (true will update the created_at and updated_at columns) and the asArray() function, the insert, update and delete functions can be used in the controller as follows:

Insert, Update and Delete

    // Create new record  app/controllers/album.php
    // with data from Form
    $album = Album::create($_POST);
    $album->insert();

    // Update record
    $album = Album::find($id);
    $album->year = 2003;
    $album->update();

    // Delete record
    $album = Album::find($id);
    $album->delete();
}

Find and GetAll

You will probably want to add a couple of basic select statements to your application's models. These two functions will return results as class Album.

    // Find by ID  app/models/album.php
    public static function find($id)
    {    
        return Db::select()
                    ->from('albums')
                    ->where('id = :id', array('id' => $id))
                    ->first('Album');        
    }

    // get all 
    public static function getAll()
    {    
        return Db::select()
                    ->from('albums')
                    ->orderBy('title')
                    ->all('Album');
    }
    
}

Now you can use the following code in your controller:

    // Index app/controllers/album.php
    function getIndex()
    {
        // get data
        $albums = Album::getAll();

        // render
        return View::make('album/index')
                        ->with('albums', $albums)
                        ->show();
    }
    

Validation

The model uses the Validation helper class to provide some basic validation for your model.

First, (in your model) define your rules ...

    // Validation rules app/models/album.php
    protected $rules = [ 
                'title'     => 'required | text',
                'year'      => 'integer | between:1900:2100',
                'artist_id' => 'integer | min:1'
                ]; 

and then (in your controller) you can fill the model with POST data from your form with fill() and then validate, as follows:

    // Fill from form app/controllers/album.php
    $album->fill($_POST);

    // validate
    if ($album->validate()) {
        // is valid
    } 

In your form you can test for errors:

  <?php if ($album->hasErrors()) : ?> app/views/album/form.php
      <div class="error">
            <p><?php echo 'Please correct the following '.
                    Date::plural($album->errors(), 'field'); ?></p>
      </div>
  <?php endif ?>  

...and display field errors:

 app/views/album/form.php
  <label for="title">Title:</label>
  <input type="text" name="title" value="<?php echo $album->title; ?>" />
  <span class="error"><?php echo $album->getError('title'); ?>
 

Model class functions

Public functions in class Model:

  // general functions core/model.php
  asArray()        // return data array (overridden in app model)

  // database functions
  insert()         // insert record based on model data
  update($id)      // update record with id=$id
  delete($id)      // delete record with id=$id
  
  // validation functions    
  validate()          // validate model with asArray() and $rules
  hasErrors()         // returns true if errors
  errors()            // return error count
  getErrors()         // return $errors array
  setRules($rules)    // set model rules
  setFieldError($field, $error) // set field error
  hasError($field)    // return true if field has error
  getError($field)    // get error description for field
  errorClass($field)  // return class="error" if field has error
  
  // PIP version 0.5 (deprecated)
  escapeString($string)
  escapeArray($array)
  to_bool($val)