Created
January 25, 2015 05:45
-
-
Save jimanx2/e6d4fad31fcce5b14c72 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| class ORM extends CI_Model { | |
| var $table_name, $fields; | |
| function __construct($subclass = NULL){ | |
| parent::__construct(); | |
| $this->load->helper('inflector'); | |
| } | |
| function initialize(){ | |
| $class = get_called_class(); | |
| $this->table_name = strtolower(plural($class)); | |
| $this->fields = $this->db->list_fields($this->table_name); | |
| } | |
| // Definition for $this->User->find($id); | |
| function find($id = null){ | |
| if (!is_integer($id)){ | |
| show_error("Cannot find User with id ".gettype($id), 500); | |
| return; | |
| } | |
| $this->db->select('*')->where("id = $id"); | |
| $query = $this->db->get($this->table_name); | |
| if (empty($query->row())){ | |
| show_error("Cannot find User with id $id"); | |
| return; | |
| } | |
| return $query->row(); | |
| } | |
| // Definition for $this->User->all(); | |
| function all(){ | |
| return $this->db->get($this->table_name)->result(); | |
| } | |
| // Definition for $this->User->find_by_(...); | |
| public function __call($func, $params) { | |
| $pos = strpos("find_by_", $func); | |
| $field = substr($func, 8); | |
| if (!($pos>=0) || !in_array($field, $this->fields)): | |
| throw new Exception("call to undefined function $func"); | |
| endif; | |
| $query = $this->db->where("$field = '${params[0]}'")->get($this->table_name); | |
| return $query->row(); | |
| } | |
| //Definition for $this->User->where(...); | |
| public function where($args){ | |
| foreach( $args as $key => $value ) { | |
| if (!in_array($key, $this->fields)): | |
| show_error("Unknown column '$key' in table $this->table_name"); | |
| return; | |
| endif; | |
| $this->db->where("$key = '$value'"); | |
| } | |
| $query = $this->db->get($this->table_name); | |
| return $query->result(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment