db = new Database( Config::$database ); if($table != false){ $this->table = $table; } } /** * * This is used to narrow down results * * @example only gather products from a specific category * $products = new Collection('tb_products', 'cat_id', $_GET['cat_id']); * * @param string $table The name of the table this collection represents * @param string $field The field to qualify which records are retrieved * */ public function get($modelType = null) { if(!is_null($modelType)){ $m = new $modelType(); $this->table = $m->table; } else if(!is_null($this->model)){ $m = new $this->model(); $this->table = $m->table; } $this->items = []; $this->db->select('*')->from($this->table); $q = $this->db->build_query(); if(Model_Provider::has($q)){ $this->items = Model_Provider::get($q); }else{ $this->items = $this->db->get(); foreach($this->items as $key => $item){ if(!is_null($modelType)){ $model = new $modelType(); } else if(!is_null($this->model)){ $model = new $this->model(); } else { $model = new Model($this->table, false); } $model->fill($item); $this->items[$key] = $model; } Model_Provider::set($q, $this->items); } } public function where($param1, $param2 = null, $param3 = null, $param4 = null){ $this->db->where($param1, $param2, $param3, $param4); return $this; } public function order_by($data, $dir = null){ $this->db->order_by($data, $dir); return $this; } public function limit($from, $count){ $this->db->limit($from, $count); return $this; } public function paginate($count, $page = 1){ $this->db->limit(($page - 1) * $count, $count); return $this; } public function pageCount($perPage){ $this->db->select('COUNT(id) as count') ->where('deleted', '0') ->from($this->table); $count = $this->db->get_field('count'); $pages = ceil($count / $perPage); return $pages; } public function __TOSTRING(){ $output = '['; $products = ''; foreach($this->items as $product){ $products .= $product.','; } return $output . substr($products, 0, -1) . ']'; } }