Completing a CodeIgniter Library with Method Chaining

In this eleventh part of a 12-part series on method chaining, I will finish building the custom CodeIgniter library we’ve been working on by adding to it some very useful features. When we’re done, the library will be able to autoload a specified model and validate input data.

True to form, method chaining is a powerful approach that lets programmers build compact and highly modular class interfaces. Of course, this methodology isn’t a proprietary feature of a particular language, which means that it can be applied quite easily in PHP 5.

Thus, if you’re a PHP developer who wishes to expand your existing skills and learn how to create and implement chainable methods when using the object-oriented paradigm, then this series of articles might be the material that you’re looking for.

Naturally, if you already had the chance to read all of the articles that precede this one, then you now have a solid background in how to create chainable interfaces in PHP 5, and how to use them for building a custom model for the CodeIgniter framework.

Speaking more specifically, in the previous article I demonstrated how to expand the functionality of this model by coding a set of chainable methods. These were tasked with building several WHERE modifiers  for appending to a given query.

As you’ll surely recall, the implementation of these methods was  a straightforward process, so it’s time to mention the topics that will be covered in this penultimate chapter of the series. Thus, as the above title suggests, in the next few lines I’m going to finish developing this custom model for CodeIgniter by adding to it some methods that will perform crucial tasks, such as automatically loading classes required by the model and validating the data required for inserting and updating database records, and building error strings and creating other common query modifiers dynamically as well.

Now, it’s the time to complete this abstract model. Let’s get going!

{mospagebreak title=Adding more chainable methods to the abstract model class}

Definitely, it’d be useful to list the full source code of the abstract model class as it was in the preceding tutorial before I start adding some other methods to it.

Given that, here’s the complete signature of the class, as a quick reminder:

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;

}

 

// Builds the JOIN part of the query

public function join($table, $join, $join_type = ”)

{

if ( !empty($table) AND !empty($join))

{

$this->db->join($table, $join, $join_type);

}

return $this;

}

 

// Builds the ORDER BY part of the query

public function order_by($field = ‘id’, $order = ‘ASC’)

{

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

{

$this->db->order_by($field, $order);

}

return $this;

}

 

// Builds the GROUP BY part of the query

public function group_by($field)

{

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

{

$this->db->group_by($field);

}

return $this;

}

 

// Builds the LIKE part of the query using the AND operator

public function like($field, $match, $position = ”)

{

if (in_array($field, $this->fields, TRUE) AND !empty($match))

{

$this->db->like($field, $match, $position);

}

return $this;

}

 

// Builds the OR LIKE part if the query using the OR operator

public function or_like($field, $match, $position = ”)

{

if (in_array($field, $this->fields, TRUE) AND !empty($match))

{

$this->db->or_like($field, $match, $position);

}

return $this;

}

 

// Builds the NOT LIKE part of the query

public function not_like($field, $match, $position = ”)

{

if (in_array($field, $this->fields, TRUE) AND !empty($match))

{

$this->db->not_like($field, $match, $position);

}

return $this;

}

 

// Builds the DISTINCT part of the query

public function distinct()

{

$this->db->distinct();

return $this;

}

 

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

}

}

If you pay attention to the above “AbstractModel” class and closely analyze the implementation of its methods, you’ll realize that despite its rather lengthy source code, its structure is actually very modular and easy to follow.

This permits you to quickly grasp how it works, so I’m going to code the methods that are charged first with building the HAVING, NOT HAVING and LIMIT sections of a query, and second with counting the rows of the database table associated with the model.

In summary, the respective definitions of these methods are as following:

// Builds the HAVING part of the query

public function having($field, $value = ”, $protect_identifiers = TRUE)

{

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

{

$this->db->having($field, $value, $protect_identifiers);

}

return $this;

}

 

// Builds the OR HAVING part of the query using the OR operator

public function or_having($field, $value = ”, $protect_identifiers = TRUE)

{

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

{

$this->db->or_having($field, $value, $protect_identifiers);

}

return $this;

}

 

// Builds the LIMIT part of the query

public function limit($limit = 0)

{

if ($limit != 0)

{

$limit = (int)abs($limit);

$this->db->limit($limit);

}

return $this;

}

 

// Determines the number of rows produced by an Active Record query

public function count_all_results($table = ”)

{

return $this->db->count_all_results($table);

}

 

// Determines the number of rows contained in a given table

public function count_all($table)

{

$table = $this->db->table_exists($table) ? $table : $this->table;

return $this->db->count_all($table);

} 

As you can see above, the first three methods are chainable also, and are simple wrappers for their counterparts defined within the native CodeIgniter database class. If you’re familiar with the class, then you shouldn’t have major problems understanding how they work.

Finally, the remaining ones aren’t chainable but perform two crucial tasks: counting the number of rows retrieved by a dynamically-generated retrieving operation, and determining the total number of rows contained in the database table associated with the model.

Well, at this point the abstract model class has become even more functional, due to the addition of the group of methods that you saw before. So, I’m going to define a couple more methods, which will accomplish two truly relevant operations: recursively autoading a specified model, and validating the data used when inserting and updating a particular database row.

These two core methods will be defined and discussed in detail in the section to come. Therefore, to learn more about them, click on the link below and keep reading.

{mospagebreak title=Autoloading models and validating incoming data}

Since the custom model class should have a loosely-coupled structure, it must be provided with the ability to recursively autoload a specified model without having to rely on other classes. Therefore, it’s necessary to define a method that performs this task.

With that requirement in mind, below I included the definition of a brand new method, not surprisingly called “autoload(),” which includes a specified class by using a combination of a simple “require_once()” PHP function and the RecursiveIteratorIterator SPL class.

Here’s how the method looks:

// Autoloads recursively child models required by the Abstract Model class

public static function autoload($model)

{

// Don’t attempt to autoload CI_ or MY_ prefixed classes

if (in_array(substr($model, 0, 3), array(‘CI_’, ‘MY_’)))

{

return;

}

// Set path and model

$path = APPPATH . ‘/models/';

$model = strtolower($model) . EXT;

// try to include recursively the model file

$rit = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));

foreach ($rit as $entry)

{

if ($model === $entry->getFileName())

{

require_once($entry->getPathname());

return;

}

}

show_error(‘Model class not found.’);

}

As you can see, the previous “autoload()” method will search recursively within the “models” folder a specified model and attempt to load it via the RecursiveIteratorIterator SPL class. If the model is found, it’ll be dynamically included by means of a “require_once()” statement. Otherwise, an error will be triggered by using the “show_error()” proprietary function of CodeIgniter.

In addition, it’s valid to point out that the implementation of the “autoload()” method is based partially on the DataMapper library developed by Simon Stenhouse. However, I’ve improved and shortened its signature by using the SPL library.

Having already explained how the custom model is capable of autoloading a specified class, it’s time to define another method, which will validate the data required for inserting and updating a database row.

This new method, called “validate(),” is protected, and its definition is shown below:

// Validates model data

protected function validate($data)

{

// If no validation rules were set trigger an error

if (empty($this->validation))

{

$this->error = ‘No validation rules were set for the model.';

return FALSE;

}

// Load CI validation library

$this->ci->load->library(‘validation’);

// Load CI language file for validation

$this->ci->lang->load(‘validation’);

// reset error messages

$this->error = array();

foreach ($this->validation as $field => $rules)

{

$exprules = explode(‘|’, $rules);

// if the field is not required check next one

if (! in_array(‘required’, $exprules, TRUE))

{

continue;

}

// Iterates through the validation rules

foreach ($exprules as $rule)

{

// Removes the parameter from the rule (when specified)

$param = FALSE;

if (preg_match("/(.*?)[(.*?)]/", $rule, $match))

{

$rule = $match[1];

$param = $match[2];

}

// Calls the validation method that corresponds to the rule

if (method_exists($this->ci->validation, $rule))

{

$result = $this->ci->validation->$rule($data[$field], $param);

}

elseif (function_exists($rule))

{

// Tries to run a native PHP function if method of CI validation class doesn’t exist

$result = $rule($data[$field]);

}

// if an offending field was found store error message in error array

if ($result === FALSE)

{

$this->error[] = sprintf($this->ci->lang->line($rule), $field);

}

}

}

return empty($this->error) ? TRUE : FALSE;

}

Despite its long definition, the above “validate()” method is quite easy to grasp. It simply validates the data that will be used when inserting and updating a database row by means of the native CodeIgniter validation library.

If the method finds the inputted data to be incorrect, it’ll return FALSE. Otherwise, it’ll return a value of TRUE. Not too difficult to understand, isn’t it?

Now that you hopefully grasped the logic that drives the previous “validate()” method, let me show you another one, which will build the corresponding error strings when the inputted data fails to pass the validation process.

Here’s the signature of this method, called “get_error_string().”

// Returns error string produced when performing validation

protected function get_error_string()

{

$str = ”;

$error_sufix = str_replace(‘<‘, ‘</’, $this->error_prefix);

foreach ($this->error as $error)

{

$str .= $this->error_prefix . $error . $error_sufix;

 }

return $str;

}

Basically, all that the previous method does is return to client code a preformatted error string, based on the “error_prefix” property initialized at the beginning of the abstract model class and nothing else.

So far, so good. At this point, I defined the remaining methods of the “AbstractModel” class that validate incoming data, autoload a specified model and finally create the corresponding error strings. Therefore, the last thing that I’m going to show you in this tutorial will be the full source code of the model class, so you can see at a glance how it looks after including the methods mentioned earlier.

This will be done in the following section, so click on the link that appears below and read the next segment.

{mospagebreak title=The final version of the abstract model class}

As I said in the previous section, here’s the complete source code that corresponds to the abstract model class, so you can see more clearly how it looks when finished:

<?php

 

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.

 

 

// register file extensions and the method that will be used for autoloading models

spl_autoload_register(NULL, FALSE);

spl_autoload_extensions(‘.php’);

spl_autoload_register(array(‘AbstractModel’,’autoload’));

 

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;

}

 

// Builds the JOIN part of the query

public function join($table, $join, $join_type = ”)

{

if ( !empty($table) AND !empty($join))

{

$this->db->join($table, $join, $join_type);

}

return $this;

}

 

// Builds the ORDER BY part of the query

public function order_by($field = ‘id’, $order = ‘ASC’)

{

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

{

$this->db->order_by($field, $order);

}

return $this;

}

 

// Builds the GROUP BY part of the query

public function group_by($field)

{

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

{

$this->db->group_by($field);

}

return $this;

}

 

// Builds the LIKE part of the query using the AND operator

public function like($field, $match, $position = ”)

{

if (in_array($field, $this->fields, TRUE) AND !empty($match))

{

$this->db->like($field, $match, $position);

}

return $this;

}

 

// Builds the OR LIKE part if the query using the OR operator

public function or_like($field, $match, $position = ”)

{

if (in_array($field, $this->fields, TRUE) AND !empty($match))

{

$this->db->or_like($field, $match, $position);

}

return $this;

}

 

// Builds the NOT LIKE part of the query

public function not_like($field, $match, $position = ”)

{

if (in_array($field, $this->fields, TRUE) AND !empty($match))

{

$this->db->not_like($field, $match, $position);

}

return $this;

}

 

// Builds the DISTINCT part of the query

public function distinct()

{

$this->db->distinct();

return $this;

}

 

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

}

 

// Builds the HAVING part of the query

public function having($field, $value = ”, $protect_identifiers = TRUE)

{

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

{

$this->db->having($field, $value, $protect_identifiers);

}

return $this;

}

 

// Builds the OR HAVING part of the query using the OR operator

public function or_having($field, $value = ”, $protect_identifiers = TRUE)

{

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

{

$this->db->or_having($field, $value, $protect_identifiers);

}

return $this;

}

 

// Builds the LIMIT part of the query

public function limit($limit = 0)

{

if ($limit != 0)

{

$limit = (int)abs($limit);

$this->db->limit($limit);

}

return $this;

}

 

// Determines the number of rows produced by an Active Record query

public function count_all_results($table = ”)

{

return $this->db->count_all_results($table);

}

 

// Determines the number of rows contained in a given table

public function count_all($table)

{

$table = $this->db->table_exists($table) ? $table : $this->table;

return $this->db->count_all($table);

}

 

// Autoloads recursively child models required by the Abstract Model class

public static function autoload($model)

{

// Don’t attempt to autoload CI_ or MY_ prefixed classes

if (in_array(substr($model, 0, 3), array(‘CI_’, ‘MY_’)))

{

return;

}

// Set path and model

$path = APPPATH . ‘/models/';

$model = strtolower($model) . EXT;

// try to include recursively the model file

$rit = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));

foreach ($rit as $entry)

{

if ($model === $entry->getFileName())

{

require_once($entry->getPathname());

return;

}

}

show_error(‘Model class not found.’);

}

 

// Validates model data

protected function validate($data)

{

// If no validation rules were set trigger an error

if (empty($this->validation))

{

$this->error = ‘No validation rules were set for the model.';

return FALSE;

}

// Load CI validation library

$this->ci->load->library(‘validation’);

// Load CI language file for validation

$this->ci->lang->load(‘validation’);

// reset error messages

$this->error = array();

foreach ($this->validation as $field => $rules)

{

$exprules = explode(‘|’, $rules);

// if the field is not required check next one

if (! in_array(‘required’, $exprules, TRUE))

{

continue;

}

// Iterates through the validation rules

foreach ($exprules as $rule)

{

// Removes the parameter from the rule (when specified)

$param = FALSE;

if (preg_match("/(.*?)[(.*?)]/", $rule, $match))

{

$rule = $match[1];

$param = $match[2];

}

// Calls the validation method that corresponds to the rule

if (method_exists($this->ci->validation, $rule))

{

$result = $this->ci->validation->$rule($data[$field], $param);

}

elseif (function_exists($rule))

{

// Tries to run a native PHP function if method of CI validation class doesn’t exist

$result = $rule($data[$field]);

}

// if an offending field was found store error message in error array

if ($result === FALSE)

{

$this->error[] = sprintf($this->ci->lang->line($rule), $field);

}

}

}

return empty($this->error) ? TRUE : FALSE;

}

 

// Returns error string when performing validation

protected function get_error_string()

{

$str = ”;

$error_sufix = str_replace(‘<‘, ‘</’, $this->error_prefix);

foreach ($this->error as $error)

{

$str .= $this->error_prefix . $error . $error_sufix;

 }

return $str;

}

}

That took a pretty long time to read, right? Don’t get tired now; you’ve learned how to apply the method chaining approach to building a PHP application that can be used in a real-world environment. Finally, before you move on and read the conclusion, feel free to introduce your own enhancements to the previous “AbstractModel” class, in case you want to use it when developing database-driven programs with CodeIgniter.

Final thoughts

That’s all for now. In this penultimate episode of the series, I finished building this custom library for CodeIgniter by adding to it some really useful features, such as the ability to autoload a specified model and validate input data as well.

However, if you’re anything like me, then a this point you may want to see how this library can be used for developing a database-driven application with CodeIgniter. In the last part of the series, I’m going to build a sample program that will reveal not only the real functionality of the library, but the convenience of using its chainable methods.

Don’t miss the next part!

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan