PHP Page 3 - Adding Ordering and Grouping Clauses to the CodeIgniter Library with Method Chaining |
In reality, it’s pretty easy to add to the previous custom model class a few additional chainable methods that build several WHERE parts of a query. To demonstrate, below I included the definitions of these concrete methods, so take some time to examine them closely. Here they are: // Builds the WHERE part of the query using AND and other operators public function get_where($where, $protect_identifiers = TRUE) { if ((is_string($where) OR is_array($where)) AND !empty($where)) { $this->db->where($where, $protect_identifiers); } return $this; }
// Builds the WHERE part of the query using OR and other operators public function get_or_where($where, $protect_identifiers = TRUE) { if ((is_string($where) OR is_array($where)) AND !empty($where)) { $this->db->or_where($where, $protect_identifiers); } return $this; }
// Builds the WHERE IN part of the query public function where_in($field, $values) { if (in_array($field, $this->fields, TRUE) AND is_array($values) AND !empty($values)) { $this->db->where_in($field, $values); } return $this; }
// Builds the WHERE NOT IN part of the query public function where_not_in($field, $values) { if (in_array($field, $this->fields, TRUE) AND is_array($values) AND !empty($values)) { $this->db->where_not_in($field, $values); } return $this; }
// Builds the OR WHERE NOT IN part of the query using the OR operator public function or_where_not_in($field, $values) { if (in_array($field, $this->fields, TRUE) AND is_array($values) AND !empty($values)) { $this->db->or_where_not_in($field, $values); } return $this; } Undoubtedly, understanding how the above methods work should be pretty straightforward, since they’ve been implemented similarly to the methods that you learned in the previous segment. Of course, in this particular case they behave as wrappers for their equivalents in the CodeIgniter database class, which makes it really easy to dynamically add several query modifiers, like WHERE, WHERE NOT IN, OR WHERE, and so forth to a given SQL query. Assuming that you already grasped the logic that drives the previous chainable methods, it’s time to list the whole source code of the abstract model class, this time including the definitions of the methods in question. This will be done in the last section of this tutorial. Therefore, go ahead and read the final segment. It’s only one click away.
blog comments powered by Disqus |
|
|
|
|
|
|
|