[eluser]Matthew Pennell[/eluser]
Thanks, Henrik - actually I think it does work okay when using the Loader class.
It's pretty easy to create an ActiveRecord class that you can then use with dynamic methods - here's my prototype code, if anyone's interested:
Code:
class ActiveRecord {
var $_parent_name = '';
function ActiveRecord()
{
$this->_assign_libraries( (method_exists($this, '__get') OR method_exists($this, '__set')) ? FALSE : TRUE );
$this->_parent_name = ucfirst(get_class($this));
log_message('debug', "ActiveRecord Class Initialized");
}
function _assign_libraries($use_reference = TRUE)
{
$CI =& get_instance();
foreach (array_keys(get_object_vars($CI)) as $key)
{
if ( ! isset($this->$key) AND $key != $this->_parent_name)
{
if ($use_reference == TRUE)
{
$this->$key = '';
$this->$key =& $CI->$key;
}
else
{
$this->$key = $CI->$key;
}
}
}
}
public function __call($method, $args)
{
if (stristr($method, 'find_by_')) {
eval('return $this->find_by("' . str_replace('find_by_', '', $method) . '", "' . $args[0] . '");');
}
if ( ! isset($args) ) eval('return $this->' . $method . ';');
eval('$this->' . $method . ' = "' . $args[0] . '";');
}
function find($id)
{
$this->db->where('id', $id);
$this->db->from(TABLE);
$query = $this->db->get();
$found = $query->row();
$query = $this->db->query('SHOW COLUMNS FROM ' . TABLE);
foreach($query->result() as $column)
{
eval('$this->' . $column->Field . ' = $found->' . $column->Field . ';');
}
}
function find_by($column, $query)
{
$this->db->where($column, $query);
$this->db->from(TABLE);
$query = $this->db->get();
$found = $query->row();
$query = $this->db->query('SHOW COLUMNS FROM ' . TABLE);
foreach($query->result() as $column)
{
eval('$this->' . $column->Field . ' = $found->' . $column->Field . ';');
}
}
}
Then by declaring the TABLE constant in your model, you automagically have access to dynamic methods like find_by_name() or find_by_postcode() - basically any fields that are in the table. You also have dynamic getter and setter methods for every table column.
Here's a basic model:
Code:
class Person extends ActiveRecord {
function Person()
{
parent::ActiveRecord();
if ( !defined('TABLE') ) define('TABLE', 'people');
}
function full_name()
{
return $this->name . ' ' . $this->surname;
}
function save()
{
if ($this->db->insert(
TABLE,
array(
'name' => $this->name,
'surname' => $this->surname
)
))
{
$this->id = $this->db->insert_id();
}
else
{
log_message('error', $this->db->last_query());
}
}
function hello()
{
echo '<p>Hello from ' . $this->full_name() . '!</p>';
}
}
Now you can do things like this:
Code:
$me = new Person();
$me->name = 'Matthew';
$me->surname = 'Pennell';
$me->save();
$foobar = new Person();
$foobar->find_by_name('Matthew');
echo 'Found ' . $foobar->full_name() . ' in the ' . TABLE . ' database!';
Obviously you can then build a lot more functionality into the ActiveRecord superclass to do complex finding, autosaving, etc. - fun stuff.