Hirazi Webtech

CodeIgniter Onboarding - Part 2 - Working with Models

Last week we introduced how to use objects in CodeIgniter while developing with your application. Posting and retrieving data is the heart of any application. While working on a MVC framework, this is abstracted under Models. The objects we created in the first part are integrated closely with the models. Before we dive into details, following points should be always kept in mind when coding models:

 

  1. Every table in your application should have a separate “model” file.
  2. The methods to be used should be generic in nature so that those can be inherited easily in other models.

 

Continuing our example from Part 1, we demonstrate how our users_model.php file looks:

<!--?php defined('BASEPATH') OR exit('No direct script access allowed'); class User_model extends CI_Model { private $table_name = ‘user’; public function __construct() { parent::__construct(); } /** * Get all users. */ public function get_all_users() { $this->db->from( $this->table_name );<br ?--> $query = $this->db->get();

if( ! $query->result_array() ) {
return array();
}

$obj_array = array_map( function( $user ) {
$obj = new \Project_Name\Objects\User( $user );
return $obj;
}, $query->result_array() );

return $obj_array;
}

/**
* Get User objects based on $query_where
* @param array $query_where: key/value pair for where clause
*/
public function get_users( $query_where ) {
$this->db->where( $query_where );
$query = $this->db->get( $this->table_name );

if( ! $query->result_array() ) {
return array();
}

$obj_array = array_map( function( $user ) {
$obj = new \Project_Name\Objects\User( $user );
return $obj;
}, $query->result_array() );

return $obj_array;
}

/**
* Returns user object if found in DB
*
* @param ID of the user
* @return false|Service_Provider Object
*/
public function get_user_by_id( $user_id ){
$this->db->from( $this->table_name )
->where( 'custId', $user_id );
$query = $this->db->get();

if( $query->row() ) {
return new \Project_Name\Objects\User( $query->row_array() );
}

return false;
}

/**
* Insert user in table
* @param array $user : key/value pair to be inserted
*/
public function insert_user( $user, $type='mobile', $force=false ) {
if( $force ) {
$this->db->insert( $this->table_name, $user );
$user_id = $this->db->insert_id();

return $this->get_user_by_id( $user_id );
}

$search_key = 'custContactNo';
if( $type == 'facebook' ) {
$search_key = 'custFbAuthId';
} else if( $type == 'google' ){
$search_key = 'custGAuthId';
}

$this->db->from( $this->table_name )
->where( $search_key, $user[ $search_key ] );

$query = $this->db->get();

//user doesn't exist. insert into table and return user object.
if( $query->num_rows() == 0 ) {
$this->db->insert( $this->table_name, $user );
$user_id = $this->db->insert_id();

return $this->get_user_by_id( $user_id );
}

return false;
}

/**
* Deletes the user from table
* @param int $user_id
*/
public function delete_user( $user_id ) {
return $this->db->delete( $this->table_name, array( 'custId' => $user_id ) );
}

/**
* Updates the fields in user table
*
* @param array $key_value: Values to be updated
* @param array $query_where: key/value pair for where clause
*/
public function update_user_field( $key_value, $query_where ) {
$this->db->set( $key_value )
->where( $query_where );

$query = $this->db->update( $this->table_name );

return $query;
}

}

?>

 

The above file creates 6 basic cruds:

  • Get all users
  • Get users based on the passed query params
  • Get user by ID
  • Insert User
  • Delete User
  • Update User

 

Get All Users

/**
* Get all users.
*/
public function get_all_users() {
$this->db->from( $this->table_name );
$query = $this->db->get();

if( ! $query->result_array() ) {
return array();
}

$obj_array = array_map( function( $user ) {
$obj = new \Project_Name\Objects\User( $user );
return $obj;
}, $query->result_array() );

return $obj_array;
}

This is a straightforward call to CodeIgniter’s get() method which returns all the entries in the table.

 

Get Users

/**
* Get User objects based on $query_where
* @param array $query_where: key/value pair for where clause
*/
public function get_users( $query_where ) {
$this->db->where( $query_where );
$query = $this->db->get( $this->table_name );

if( ! $query->result_array() ) {
return array();
}

$obj_array = array_map( function( $user ) {
$obj = new \Project_Name\Objects\User( $user );
return $obj;
}, $query->result_array() );

return $obj_array;
}

This method accepts $query_where as an argument, which is basically an array of key/value pairs. Say you want to get the users with name:”jitendra” (where name is the column key in the User table), you will call the method like:
get_users( array( ‘name’ => ‘jitendra’ ) );

 

Get User By ID

/**
* Returns user object if found in DB
*
* @param ID of the user
* @return false|Service_Provider Object
*/
public function get_user_by_id( $user_id ){
$this->db->from( $this->table_name )
->where( 'custId', $user_id );
$query = $this->db->get();

if( $query->row() ) {
return new \Project_Name\Objects\User( $query->row_array() );
}

return false;
}

The reason we create this method instead of having a get_users method where we can pass ID/value as an argument is to denormalize our code as most of the tables (related to user) will have an ID attribute as their foreign key. So, we will retrieve user information multiple times based on ID. Having a separate method improves readability.

 

Insert User

/**
* Insert user in table
* @param array $user : key/value pair to be inserted
*/
public function insert_user( $user, $type='mobile', $force=false ) {
if( $force ) {
$this->db->insert( $this->table_name, $user );
$user_id = $this->db->insert_id();

return $this->get_user_by_id( $user_id );
}

$search_key = 'custContactNo';
if( $type == 'facebook' ) {
$search_key = 'custFbAuthId';
} else if( $type == 'google' ){
$search_key = 'custGAuthId';
}

$this->db->from( $this->table_name )
->where( $search_key, $user[ $search_key ] );

$query = $this->db->get();

//user doesn't exist. insert into table and return user object.
if( $query->num_rows() == 0 ) {
$this->db->insert( $this->table_name, $user );
$user_id = $this->db->insert_id();

return $this->get_user_by_id( $user_id );
}

return false;
}

As the name suggest, this method is used to insert a new row in the table. This accepts multiple parameters:
$user => an array of key/value pairs to be inserted
$type => type of the user, meaning, is he a regular user (email/phone registration) or a facebook/google registration.
$force => to forcibly insert a duplicate entry

Depending upon the type we decide which key to check duplicates, but if $force is true we insert a new row in the table.

 

Delete User

/**
* Deletes the user from table
* @param int $user_id
*/
public function delete_user( $user_id ) {
return $this->db->delete( $this->table_name, array( 'custId' => $user_id ) );
}

Another straightforward method to delete the row from the table.

 

Update User

/**
* Updates the fields in user table
*
* @param array $key_value: Values to be updated
* @param array $query_where: key/value pair for where clause
*/
public function update_user_field( $key_value, $query_where ) {
$this->db->set( $key_value )
->where( $query_where );

$query = $this->db->update( $this->table_name );

return $query;
}

This method is to update a specific column field in the table. It accepts couple of parameters:
$key_value: key/value pair to update
$query_where: key/value pair to search

 

Using Objects with Models

CodeIgniter’s database library is used to make above calls. The result is an array of Users with key/value pair as defined in the database. The magic lies in instantiating the User objects from the retrieved result which will make it easy to use the user information anywhere in the project without remembering the database keys. As explained in the previous part, User object class accepts one parameter (an array) to set its properties, which can then be retrieved by using getters.

$obj = new \Project_Name\Objects\User( $user );
return $obj;

 

Most of the applications won’t need any other queries than basic cruds defined above. Depending upon the complexity of the functionality you are trying to build, you can either decide to retrieve the information using the basic queries and then, manipulating the information in your controller (coming up in the next part) or you can write specific queries to return the required information. The gist of this style is to always return the objects of the table you are working with.

 

That’s it! Now working with model is as simple as it can get. Next we will explain how to work with Controllers.

Link to social platforms of Hirazi Webtech

We like to spread happiness. Let's do it together.

Contact details of Hirazi Webtech

Get in Touch

Would love to hear you over coffee!

Contact Detail

Hirazi Webtech

Mumbai, India

+91 96994-53388

contact.us@hirazi.com