Expanding a Custom CodeIgniter Library with Method Chaining

Welcome to the eighth installment of a series on method chaining in PHP 5. With numerous code samples, this series shows you how to define chainable methods within your own PHP classes. Best of all, it teaches you how to implement this powerful programming method in a real-world case: developing an abstract model for the CodeIgniter framework.

Naturally, if you already read the preceding article of the series, at this point you have a clearer idea of how to apply the method chaining approach to building a customized model class for CodeIgniter. In that tutorial I started to create such a class. It had the ability to fetch and insert/update the records of an associated database table through a few methods, some of which were chainable.

However, as you might have guessed, this CodeIgniter class has a rather limited functionality in its current state. Therefore, in this tutorial of the series I’m going to add more methods to it, which will permit it to delete database rows, as well as build different portions of SELECT statements. And guess what? These last methods will be chainable too!

Now, it’s time to begin coding the methods for this custom CodeIgniter library. Let’s jump in!

{mospagebreak title=Review: the delete() method}

Prior to coding these new methods, I’m going to reintroduce the signature of the “AbstractModel” class as it was in the previous tutorial. Here is the full source code for the class. Please look it over: 

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;

}

}

Hopefully, after having reexamined the definition of the previous “AbstractModel” class, you’ll recall how its current methods were implemented. In this case, it’s clear to see how the method chaining approach has been applied to build the “factory()” and “fetch()” methods, which speaks for itself about the functionality of this technique.

So far, so good. Now, it’s time to continue expanding the functionality of the custom model for CodeIgniter, since at this time it’s only capable of fetching and inserting/updating database rows. Therefore, I’m going to add another method, which will be tasked with deleting records.

The implementation of this brand new method, not surprisingly called “delete(),” is shown below. Look at it, please:

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

}

Short and effective, right? As you can see, the above “delete()” method is tasked with removing a specified row or rows from the corresponding database table. If this operation fails for whatever reason, the method will store an error message on the “error” property and returns a value of FALSE. Otherwise, it’ll return TRUE.

Having now provided the custom model for CodeIgniter with the ability to delete database records, it’s time to extend its current functionality even more. In the section to come I’m going to add to the model a couple of chainable methods, which as you’ll see in short, will be capable of building the SELECT and SELECT MAX part of a SQL query.

Thus, to learn the full details on how these new methods will be created, click on the link below and keep reading.

{mospagebreak title=The chainable select() and select_max() methods}

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.

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

Certainly, the best way to understand how the “AbstractModel” class does its business is by showing its entire source code, including the pair of chainable methods that were defined in the previous section.

With that idea in mind, below I’ve included the class, so you can see at a glance how it looks. Here it is:

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;

}

}

There you have it. At this stage, the above “AbstractModel” class looks much more functional due to the incorporation of the “select()” and “select_max()” methods, which can be easily chained to others as well. As usual, feel free to edit the class’s source code and introduce your own enhancements. That will be a good exercise for improving your understanding of method chaining in PHP 5.

Final thoughts

That’s it for now. Over this eighth chapter of the series, I defined and implemented a few more methods for the custom CodeIgniter model class. As you saw for yourself, some of these methods are chainable, which hopefully demonstrates the actual benefits of using this programming methodology.

In the next episode, things will become even more interesting. I’m going to define more chainable methods within the model class, which will allow you to create the SELECT MIN, SELECT AVG and SELECT SUM parts of a SQL query.

Therefore, here’s my final suggestion: don’t miss the upcoming part!

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

chat