Webthink-Julian
By: a guest | May 1st, 2008 | Syntax:
PHP | Size: 1.38 KB | Hits: 16 | Expires: Never
/**
* Magic method for getting object and model keys.
*
* @param string key name
* @return mixed
*/
public function __get($key)
{
if (isset($this->object->$key))
{
return $this->object->$key;
}
//this condition doesn't need to be here but ensures we don't loop needlessly
if ( ! empty($this->object->id))
{
$foreign_table = FALSE;
foreach ($this->has_one + $this->belongs_to as $table)
{
if ( $foreign_table == FALSE AND
$table == substr ($key,0
-strlen($table)) )
{
$foreign_table = $table;
}
}
}
if ( ! empty($this->object->id) AND
$foreign_table !== FALSE )
{
// Set the model name
$model = ucfirst($foreign_table).'_Model';
// Set the child id name
$child_id = $key.'_id';
if (isset($this->object->$child_id))
{
// Get the foreign object using the key defined in this object
return $this->object->$key = new $model($this->object->$child_id);
}
else
{
// Get the foreign object using the primary key of this object
return $this->object->$key = new $model(array($this->class.'_id', $this->object->id));
}
}
else
{
switch($key)
{
case 'table_name':
return $this->table;
break;
case 'class_name':
return $this->class;
break;
case 'auto_save':
return $this->auto_save;
break;
}
}
}