Building a Sample Application with Method Chaining and CodeIgniter

Definitely, building chainable class methods with PHP 5 is a process that can be mastered with minor effort, even for developers with only an average level of experience in using the object-oriented paradigm. Therefore, if you’re a passionate PHP programmer who wishes to learn the key concepts that surround the implementation of method chaining in a painless fashion, then this group of articles is what you need.

Welcome to the final part of a series that covers method chaining in PHP 5. In twelve tutorials, this series attempts to teach you the basics of building chainable class methods with PHP 5 and complements the corresponding theory with copious hands-on examples.

And now that you’ve come to this point, it’s time to summarize the topics that were covered in the last tutorial. In that particular article I finished building a custom model library for the popular CodeIgniter framework, where most (not all) of its functionality relied on the definition and implementation of chainable methods. That speaks for itself about the convenience of using this programming approach.

It’s valid to say, though, that this custom library would be pretty useless if I didn’t show you how to utilize it in the context of a database-driven application. Therefore, this last installment of the series will be aimed at demonstrating how to build a simple PHP program with CodeIgniter that will perform CRUD operations on a simple MySQL table that will store data on some fictional users.

Now, it’s time to stop talking and get our hands dirty building this basic – yet illustrative — PHP program.

{mospagebreak title=Review: the abstract model class so far}

Before I develop the sample database-driven application that I mentioned in the introduction, it’d be very helpful to list the complete source code of the abstract model class created in the previous tutorials. In this way you can recall how it looked when finished.

Ready to digest a lengthy piece of code? Then look at the class below:

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

}

}

Here you have the full source code of the abstract model class at your disposal. But wait a minute! Before I move forward, don’t forget to edit the autoload.php configuration file of CodeIgniter to make sure the class will be included automatically by the framework.

Okay, since the "AbstractModel" class encapsulates all of the functionality required for performing the most common database-related operations, as well as for validating incoming data, I am now going to create a subclass from the model, which will be associated automatically with a "users" MySQL table.

As its name suggests, this table will contain three fields for storing users’ first and last names, and their email addresses. Based on this simple schema, the subclass that I’m about to create is going to consider the two first fields as required. Its short signature will be as follows:

<?php

class User extends AbstractModel

{

public function __construct()

{

parent::__construct();

$this->validation = array(‘firstname’ => ‘required’, ‘lastname’ => ‘required’);

}

}

?> 

That was quick to code and read, right? At this point, there’s a model called "User" that will handle the data stored on a "users" MySQL table, which also will require entering non-empty strings for the "firstname" and "lastname" fields.

Now that the model class has been properly defined, it should be saved as "user.php" under the "/models/" folder of the CodeIgniter installation. Done? Nice. So, it’s time to create the corresponding "Users" controller, whose skeleton will look like this:

<?php

class Users extends Controller

{

// constructor

public function Users()

{

parent:: Controller();

$this->load->helper(‘url’);

}

 

// list all users

public function index()

{

// code for listing users goes here

}

 

// save a new user

public function save()

{

// code for saving a user goes here

}

 

// update an existing user

public function update()

{

// code for updating a user goes here

}

 

// delete an existing user

public function delete()

{

// code for deleting a user goes here

}

}

?>

Undeniably, the bare bones structure of the "Users" controller is pretty self-explanatory. It defines four methods, apart from the constructor, for retrieving all of the users stored on the MySQL table, inserting and updating existing ones, and finally for deleting them.

So far, these methods have no explicit implementation, but should give you an appropriate idea of how the controller is going to handle user-related records. Still don’t have a clue about this? Well then, it’s time to start adding some logic to them, to dissipate your doubts.

This process will be discussed in detail in the section to come. Therefore, click on the link below and read the next few lines.

{mospagebreak title=Adding functionality to the Users controller class}

As I stated in the previous segment, I’m going to implement the first two methods of the "Users" controller to retrieve all of the users stored on the MySQL table, and to insert a new one.

That being explained, here’s how these methods now look:

// list all users

public function index()

{

$data['users'] = AbstractModel::factory(‘User’)->order_by(‘id’)->fetch();

$data['title'] = ‘User List';

$data['heading'] = ‘List of available users';

$this->load->view(‘users_view’, $data);

}

 

// save a new user

public function save()

{

$user = AbstractModel::factory(‘User’);

$user->firstname = ‘Wendy';

$user->lastname = ‘Torrance';

$user->email = ‘wendy@torrance.com';

if ($user->save())

{

redirect (‘/users’);

}

$this->load->view(‘error_view’, array(‘error’ => $user->error));

}

As shown above, the "index()" method demonstrates how helpful the chainable methods of the custom model can be. It uses only one line of code to fetch all the users from the corresponding MySQL table. In this case, I decided to call the "factory" method to create an instance of the model, but you may want to directly use its constructor instead.

Once the index method has retrieved the data from the MySQL table, it’s directly embedded into a new view file called "users_view," for displaying purposes. Later on, I’m going to list the definition of this file, so don’t worry about it for the moment.

Now, regarding the definition of the "save()" method, it first creates a new user, then assigns to the object the corresponding properties, and finally saves this data to the database table. Also, you may have noticed that, again, I used the "factory()" method to create a new user.

Why did I do this, instead of creating the user object only once? I did it only to keep the code of each method uncluttered. But to do things more correctly, an instance of the user model should be created in the constructor and stored as a property of the controller, thus making it accessible to all of its methods.

Now that you hopefully understood how the previous methods do their things, it’s time to code the remaining ones, which will be tasked with updating and deleting an existing user.

This process will be discussed in the last section of this tutorial. So click on the link below and keep reading.

{mospagebreak title=Finishing the controller class with update and delete methods}

The last two methods of the "Users" controller that still have no concrete implementation are the ones responsible for updating and deleting users respectively. Therefore, it’s necessary to turn them into functional structures quickly.

Based on this requirement, below I included the definitions of these methods, which look like this:

// update an existing user

public function update()

{

$user = AbstractModel::factory(‘User’);

$user->firstname = ‘Daniel';

$user->lastname = ‘Torrance';

$user->email = ‘danny@torrance.com';

$user->id = 1;

if ($user->save())

{

redirect (‘/users’);

}

$this->load->view(‘error_view’, array(‘error’ => $user->error));

}

 

// delete an existing user

public function delete()

{

$user = AbstractModel::factory(‘User’);

$user->id = 1;

if ($user->delete())

{

redirect (‘/users’);

}

$this->load->view(‘error_view’, array(‘error’ => $user->error));

}

Certainly, the methods shown above should be very easy for you to grasp, since they look quite similar to the ones coded in the previous section. In this case, once a particular user has been successfully updated or deleted, a redirection will take place, and the list of users will be automatically refreshed.

If, for some reason, these operations fail, an error message will be displayed on screen by using the following view file:

(‘error_view.php’ file)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>An error was found!</title>

</head>

<body>

<h2>The following error occurred:</h2>

<?php echo $error;?>

</body>

</html>

In addition, here’s the view responsible for displaying the list of users stored on the MySQL database table:

(‘users_view.php’ file)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>User List</title>

</head>

<body>

<h1><?php echo $heading;?></h1>

<?php foreach ($users->result as $user):?>

<p><?php echo ‘First Name: ‘ . $user->firstname;?></p>

<p><?php echo ‘Last Name: ‘ . $user->lastname;?></p>

<p><?php echo ‘Email: ‘ . $user->email;?></p>

<hr />

<?php endforeach?>

</body>

</html>

And with this last code sample, the development of this sample database-driven application is finished. Of course, as you may have guessed, it’s possible to define additional methods inside the controller that display, for instance, the full details of a specified user.

To do this in a simple manner, you might want to use some of the chainable methods provided by the generic model class and build the correct query dynamically. But this will be left as homework for you. Meanwhile, feel free to play with all of the code samples included in this tutorial, to give yourself a better background in using method chaining in PHP 5.

Final thoughts

It’s hard to believe, but we’ve come to the end of this series. In these 12 tutorials you’ve hopefully learned how to define and implement chainable methods in PHP 5.

Ranging from building simple classes that parse strings and abstract accesses to MySQL, to developing a full-featured custom model class for CodeIgniter, method chaining is a powerful approach that will help you to create compact — yet readable — class APIs with minor effort.

See you in the next PHP development tutorial!

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