It would be useful to provide the previous “AbstractModel” class with the capacity to separately build the SELECT and SELECT MAX parts of a SQL query. To do so, I’m going to create a couple of chainable methods that will perform this task in a truly modular way. Essentially, these methods are simple proxies for their counterparts defined within the CodeIgniter database class, and their respective implementations are as follows: // Builds SELECT part of the query public function select($select = '*', $protect_identifiers = TRUE) { if ($select != '*' AND !empty($select)) { $select = explode(',', $select); foreach ($select as $key => $field) { if ( !in_array($field, $this->fields, TRUE)) { unset($select[$key]); } } $select = !empty($select) ? $select : '*'; } $this->db->select($select, $protect_identifiers); return $this; }
// Builds the select MAX part of the query public function select_max($field, $alias = '') { if (in_array($field, $this->fields, TRUE)) { $this->db->select_max($field, $alias); } return $this; } Undoubtedly, the custom model class is starting to take shape with the addition of the two chainable methods defined previously. As you can see, the first one will build the SELECT portion of a SQL query, while the last one will create the SELECT MAX part, making it possible to chain them with others very easily. Well, at this stage you hopefully learned how to apply the method chaining approach to extending the functionality of the previous custom model class for CodeIgniter. In the last part of this article I’m going to list the complete source code of the model, this time including the additional methods created today. What are you waiting for? Go ahead and read the next few lines.
blog comments powered by Disqus |
|
|
|
|
|
|
|