Skip to content

Instantly share code, notes, and snippets.

@xiankai
Created October 3, 2013 09:46

Revisions

  1. xiankai created this gist Oct 3, 2013.
    71 changes: 71 additions & 0 deletions Builder Pattern
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,71 @@
    <?php

    class ORMModel extends CI_Model {

    public function __construct() {
    parent::__construct();
    }

    public function __call($name, $args) {
    $method = strtolower(substr($name, 0, 3));
    $object = substr($name, 3);

    // Parsing arguments
    $params = (isset($args[0])) ? $args[0] : array();
    $single = (isset($args[1])) ? $args[1] : false;
    $count = (isset($args[2])) ? $args[2] : false;
    $page = (isset($args[3])) ? $args[3] : '';
    $per_page = (isset($args[4])) ? $args[4] : '';

    if ($method === 'get') {
    $this->db->from($object);
    } elseif ($method !== 'set') {
    throw new Exception('Unsupported method ' . $name);
    }

    if (method_exists($this, $name)) {
    $this->{$name}($params);
    } elseif ($method === 'get') {
    $this->__getter($params);
    } else {
    $this->__setter($params);
    };

    if ($method === 'set') {
    // Insert on duplicate method, for both insert/updates, this way the SET can become of the WHERE
    return $this->db->on_duplicate($object);
    }

    $this->db->limit($per_page, $page);
    $result = $this->db->get();
    if (!$result) {
    throw new Exception('No result from ' . $name);
    }

    if ($count) {
    return $result->num_rows;
    }

    if ($single) {
    return $result->row_array();
    } else {
    return $result->result_array();
    }
    }

    private function __getter($params) {
    foreach ($params as $field => $value) {
    if (method_exists($this, $field)) {
    $this->where{$field}($value);
    }
    $this->db->where_in($field, $value);
    }
    }

    private function __setter($params) {
    foreach ($params as $field => $value) {
    $this->db->set($field, $value);
    }
    }

    }