PS: Don’t forget to include (if you so choose) get_once(), get_by_id() and I also user is_new() a lot. I also thought a clone() and copy() function would be useful, all are listed below:
/**
* Get Once
*
* Gets this object if it hasn't already been gotten.
* Only used in relationships.
*
* @access public
* @return $this
*/
function get_once()
{
if( $this->is_new() && !empty($this->related))
{
$this->get();
}
return $this;
}
// --------------------------------------------------------------------
/**
* Is New
*
* Returns TRUE if this model has not been saved (has no id).
*
* @access public
* @return TRUE if this model has not been saved
*/
function is_new()
{
return empty($this->id);
}
// --------------------------------------------------------------------
/**
* Get By Id
*
* Gets an object by id.
*
* @access public
* @param int id of object
* @return $this
*/
function get_by_id($id)
{
return $this->where('id', intval($id))->get();
}
// --------------------------------------------------------------------
/**
* Get Clone
*
* Creates a clone of this object, and returns it
* Clones are exact duplicates, including the id.
*
* @access public
* @return clone, or NULL if id has not been set
*/
function get_clone()
{
$clone = NULL;
// try to get this object, if it is in a relationship
$this->get_once();
if( ! empty($this->id)) {
$m = ucfirst($this->model);
$clone = new $m();
$clone->get_by_id($this->id);
}
return $clone;
}
// --------------------------------------------------------------------
/**
* Get Copy
*
* Creates a copy of this object, and returns it
* Copies are new objects, that have not yet been stored in the database.
*
* @access public
* @param save if TRUE, saves the new value in the database immediately.
* @return clone, or NULL if id has not been set
*/
function get_copy($save = FALSE)
{
$m = ucfirst($this->model);
$copy = new $m();
// try to get this object, if it is in a relationship
$this->get_once();
foreach($this->fields as $field)
{
$copy->{$field} = $this->{$field};
}
if($save)
{
$copy->save();
}
return $copy;
}