Method Chaining: Adding More Selecting Methods to the CodeIgniter Library

In this ninth part of an 11-part series on method chaining, I will add three new chainable methods to the custom CodeIgniter model class we built in previous parts. You should find this a straightforward process, especially if you have a decent background in this framework’s database class.

While it’s not going to change forever the way that PHP developers build their web applications, method chaining is a solid programming approach that permits them to build classes that have highly compact and modular interfaces.

So, if you’re always looking for new ways to improve your existing development skills and want to learn how to incorporate chainable methods into your PHP programs, then you should read this series of articles. In it you’ll find a guide that will show you how to accomplish this in a truly friendly fashion.

However, if you’ve been a patient reader and have already read the previous installments, then you now have a solid background in creating chainable methods with PHP 5. In those tutorials I not only explained how to implement this kind of method, but how to use them for developing a custom model library for CodeIgniter.

Now, speaking more specifically, in the preceding article I added a couple of chainable methods to the aforementioned CodeIgniter model for building the SELECT and SELECT MAX parts of a SQL query. They expanded the model’s current functionality.

Nonetheless, it’s fair to say that there is still plenty of room for expanding the capabilities of the model. Therefore, in the course of this ninth part of the series I’m going to code a couple of additional chainable methods to it that will be tasked with building the SELECT MIN, SELECT SUM and SELECT AVG parts of a SELECT SQL statement respectively.

So, want to see how these brand new methods will be coded? Then, get rid of the preliminaries and start reading right now!

{mospagebreak title=Review: the AbstractModel class’s source code}

Before I proceed to define the set of chainable methods that will be tasked with creating the SELECT MIN, SELECT SUM and SELECT AVG sections of a SQL statement respectively, I’m going to reintroduce the complete source code of the “AbstractModel” class as it was in the previous article. 

Here’s the class in question:

The MIT License

 

Copyright (c) 2008 Simon Stenhouse

 

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

 

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

 

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

 

class AbstractModel

{

protected $table = ”;

protected $fields = array();

protected $validation = array();

protected $error_prefix = ‘<p>';

protected static $instance = NULL;

protected $ci = NULL;

protected $db = NULL;

 

// Factory method that creates a singleton model object

public static function factory($model)

{

if (self::$instance == NULL)

{

$model = ucfirst($model);

self::$instance = new $model;

}

return self::$instance;

}

 

// Constructor

public function __construct()

{

$this->ci = & get_instance();

$this->db = $this->ci->db;

$table = strtolower(get_class($this)) . ‘s';

if ($this->db->table_exists($table))

{

$this->table = $table;

$this->fields = $this->db->field_names($this->table);

}

else

{

return;

}

}

 

// Sets a new property for the model

function __set($property, $value)

{

if(in_array($property, array_merge($this->fields, array(‘error’, ‘result’)), TRUE))

{

$this->$property = $value;

}

}

 

// Gets the value of an existing property of the model

function __get($property)

{

if(isset($this->$property))

{

return $this->$property;

}

return NULL;

}

 

// Fetches rows from specified table

public function fetch($limit = NULL, $offset = NULL)

{

$data = array();

foreach ($this->fields as $field)

{

if (isset($this->$field) AND $this->$field != ”)

{

$data[$field] = $this->$field;

}

}

$query = !empty($data) ? $this->db->get_where($this->table, $data, $limit, $offset) : $this->db->get($this->table, $limit, $offset);

if ($query->num_rows() > 0)

{

$this->result = $query->result();

return $this;

}

$this->error = ‘No rows were returned.';

return FALSE;

}

 

// Inserts a new row into the specified database table

public function save()

{

$data = array();

foreach ($this->fields as $field)

{

if (isset($this->$field))

{

$data[$field] = $this->$field;

 

}

}

// if there is any data available go ahead and save/update row

if( !empty($data))

{

// validate input data

if ($this->validate($data) === FALSE)

{

$this->error = $this->get_error_string();

return FALSE;

}

// if id property has been set in the controller update existing row

if ( !empty($this->id))

{

// Update existing record

$this->db->where(‘id’, $this->id);

$this->db->update($this->table, $data);

}

else

{

// otherwise insert new row

$this->db->insert($this->table, $data);

$this->id = $this->db->insert_id();

}

return TRUE;

}

$this->error = ‘No valid data was provided to save row.';

return FALSE;

}

 

// Deletes a row

public function delete()

{

if (isset($this->id))

{

$this->db->where(‘id’, $this->id);

$this->db->delete($this->table);

return TRUE;

}

$this->error = ‘Error deleting row.';

return FALSE;

}

 

// 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;

}

}

Despite its rather lengthy source code, the above model class is pretty easy to follow. Its methods are very modular and perform well-differentiated tasks. Logically, its strongest point is the implementation of several methods that can be easily chained to each other to create different portions of a query.

Well, now that you remember how the “AbstractModel” class does its thing, it’s time to continue extending its existing functionality. In the section to come I’m going to define three new chainable methods, which will be used for calculating the minimal, average and sum values of a database table column.

To learn more about how these methods will be implemented, click on the link below and read the next few lines.

{mospagebreak title=Building the SELECT MIN, SELECT AVG and SELECT SUM parts of a SQL statement with chainable methods}

In reality, creating methods that build the SELECT MIN, SELECT AVG and SELECT SUM parts of a SELECT SQL query doesn’t differ too much from building the one tasked with constructing a SELECT MAX portion. In this case, the methods will be able to be chained also, since they’ll return an instance of the abstract model class.

Now it’s time to see how these brand new methods look. Here they are:

// Builds the select MIN part of the query

public function select_min($field, $alias = ”)

{

if (in_array($field, $this->fields, TRUE))

{

$this->db->select_min($field, $alias);

}

return $this;

}

 

// Builds the select AVG part of the query

public function select_average($field, $alias = ”)

{

if (in_array($field, $this->fields, TRUE))

{

$this->db->select_min($field, $alias);

}

return $this;

}

 

// Builds the select SUM part of the query

public function select_sum($field, $alias = ”)

{

if (in_array($field, $this->fields, TRUE))

{

$this->db->select_min($field, $alias);

}

return $this;

}

Certainly, if you take a closer look at the implementation of the above three methods, you’ll realize quickly that they’re simple proxies for their counterparts defined within the CodeIgniter database class (assuming that you’re already pretty familiar with it, of course).

So, after creating the appropriate SELECT parts of a query, they’ll return to client code an instance of the “AbstractModel” class, in this way turning themselves into chainable interfacing elements. Not too hard to grasp, right?

At this point, it’s fair to say that the model class has became much more functional, especially with the addition of the last three methods. However, the best way to see how these fit with the rest of the class’s code consists of showing the full signature of the class.

That’s precisely what I’m going to do in the last section of this tutorial, so go ahead and read the next few lines.

{mospagebreak title=The AbstractModel class’s updated source code}

As I sated in the section that you just read, below I listed the complete source code corresponding to the previous “AbstractModel” class, this time including the three chainable methods that were discussed earlier. Look at it, please:

The MIT License

 

Copyright (c) 2008 Simon Stenhouse

 

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

 

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

 

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

 

 

class AbstractModel

{

protected $table = ”;

protected $fields = array();

protected $validation = array();

protected $error_prefix = ‘<p>';

protected static $instance = NULL;

protected $ci = NULL;

protected $db = NULL;

 

// Factory method that creates a singleton model object

public static function factory($model)

{

if (self::$instance == NULL)

{

$model = ucfirst($model);

self::$instance = new $model;

}

return self::$instance;

}

 

// Constructor

public function __construct()

{

$this->ci = & get_instance();

$this->db = $this->ci->db;

$table = strtolower(get_class($this)) . ‘s';

if ($this->db->table_exists($table))

{

$this->table = $table;

$this->fields = $this->db->field_names($this->table);

}

else

{

return;

}

}

// Sets a new property for the model

function __set($property, $value)

{

if(in_array($property, array_merge($this->fields, array(‘error’, ‘result’)), TRUE))

{

$this->$property = $value;

}

}

 

// Gets the value of an existing property of the model

function __get($property)

{

if(isset($this->$property))

{

return $this->$property;

}

return NULL;

}

 

// Fetches rows from specified table

public function fetch($limit = NULL, $offset = NULL)

{

$data = array();

foreach ($this->fields as $field)

{

if (isset($this->$field) AND $this->$field != ”)

{

$data[$field] = $this->$field;

}

}

$query = !empty($data) ? $this->db->get_where($this->table, $data, $limit, $offset) : $this->db->get($this->table, $limit, $offset);

if ($query->num_rows() > 0)

{

$this->result = $query->result();

return $this;

}

$this->error = ‘No rows were returned.';

return FALSE;

}

 

// Inserts a new row into the specified database table

public function save()

{

$data = array();

foreach ($this->fields as $field)

{

if (isset($this->$field))

{

$data[$field] = $this->$field;

 

}

}

// if there is any data available go ahead and save/update row

if( !empty($data))

{

// validate input data

if ($this->validate($data) === FALSE)

{

$this->error = $this->get_error_string();

return FALSE;

}

// if id property has been set in the controller update existing row

if ( !empty($this->id))

{

// Update existing record

$this->db->where(‘id’, $this->id);

$this->db->update($this->table, $data);

}

else

{

// otherwise insert new row

$this->db->insert($this->table, $data);

$this->id = $this->db->insert_id();

}

return TRUE;

}

$this->error = ‘No valid data was provided to save row.';

return FALSE;

}

 

// Deletes a row

public function delete()

{

if (isset($this->id))

{

$this->db->where(‘id’, $this->id);

$this->db->delete($this->table);

return TRUE;

}

$this->error = ‘Error deleting row.';

return FALSE;

}

 

// 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;

}

 

// Builds the select MIN part of the query

public function select_min($field, $alias = ”)

{

if (in_array($field, $this->fields, TRUE))

{

$this->db->select_min($field, $alias);

}

return $this;

}

 

// Builds the select AVG part of the query

public function select_average($field, $alias = ”)

{

if (in_array($field, $this->fields, TRUE))

{

$this->db->select_min($field, $alias);

}

return $this;

}

 

// Builds the select SUM part of the query

public function select_sum($field, $alias = ”)

{

if (in_array($field, $this->fields, TRUE))

{

$this->db->select_min($field, $alias);

}

return $this;

}

}

Hopefully, with the complete source code of the above model class at your disposal, you’ll be able to grasp more quickly how each of its methods work, and how the method chaining approach has been used to implement them appropriately.

Finally, feel free introduce your own improvements to this custom CodeIgniter library to enhance its current functionality. The experience will be instructive and fun, trust me.

Final thoughts

That’s about it for the moment. In this ninth episode of the series, I added three new chainable methods to the custom CodeIgniter model class. This is certainly a process that should be pretty straightforward for you, especially if you have a decent background in this framework’s database class.

Moving forward, in the upcoming tutorial I’m going to keep adding more chainable methods to the class. These will be tasked with building the ORDER BY, LIKE, NOT LIKE and DISTINCT portions of a query.

Don’t miss the next part!

[gp-comments width="770" linklove="off" ]

chat sex hikayeleri Ensest hikaye