使用ORM样式在CodeIgniter中编写模型类

I thought about using an actual ORM like Doctrine, then I figured its download link was even broken...and all tutorials online dated back to 2011. Also I'll have to write yaml files.

Then I start off by trying to write my own model class in ORM style.

I just fill it up with fields and save it to database, which is easy.

But I encounter a problem trying to retrieve data from database.

class User extends CI_Model {

    public $id;
    public $email;
    public $displayName;

 public function save() {
  .....
 }

public function search_by_email($email) {
    $user = new User();
    $this->db->select('email')->from('user')->where('email', $email);
    $result = $this->db->get();
    if ($result->num_rows()==0) {
        return false;
    }else {
        foreach ($result->result() as $field) {

        }
    }
}

I know normally in CodeIgniter, you return $query->result(), well as ORM custom, I'm trying to return an object...Is there a way to do this? What function should I use?

result takes a string that represents a class that it will instantiate and assigned the result data (each field as a property of the object):

$query = $this->db->query("SELECT * FROM users;");

foreach ($query->result('User') as $row)
{
   echo $row->name; // call attributes
   echo $row->reverse_name(); // or methods defined on the 'User' class
}

regarding your comment, i'm pretty sure that codeigniter has no idea about anything regarding the class you pass to the result method. It looks like it just instantiates it and sets property and valuefor each column/value returned from the db:

$this->custom_result_object[$class_name][$i] = new $class_name();

foreach ($this->{$_data}[$i] as $key => $value)
{
    $this->custom_result_object[$class_name][$i]->$key = $value;
}

One ORM that works quite well with codeIgniter is php-activerecord which is based off the rails active record model.

The function your trying to copy "search_by_email" is done through a

Late static binding method.

So you might see functions that are called like so:

Object::find_by_email()

Object::search_by_email()