Return to Snippet

Revision: 20379
at February 16, 2010 16:26 by Abe


Updated Code
<?php if (!defined('BASEPATH')) exit('No direct script access');

class Users_model extends Model {
	var $table = 'users';
	
	function __construct() {
		parent::Model();
	}
	
	function Users_model() {
		parent::Model();
	}
	
	function add_user($options = array()) {
		if(!$this->_required(array('email', 'password'), $options))
			return false;
			
		$options = $this->_default(array('status' => 'active'), $options);
		
		$qualificationArray = array('email', 'username', 'status');
		foreach($qualificationArray as $qualifier) {
			if (isset($options[$qualifier]))
				$this->db->set($qualifier, $options[$qualifier]);
		}
		
		if (isset($options['password']))
			$this->db->set('password', md5($options['password']));
			
		$this->db->insert($this->table);
		
		return $this->db->insert_id();
	}
	
	function update_user($options = array()) {
		if(!$this->_required(array('email'), $options))
			return false;
			
		$qualificationArray = array('email', 'username', 'status');
		foreach($qualificationArray as $qualifier) {
			if (isset($options[$qualifier]))
				$this->db->set($qualifier, $options[$qualifier]);
		}
		
		$this->db->where('email', $options['email']);
		
		if(isset($options['password']))
			$this->db->set('password', md5($options['password']));
			
		$this->db->update($this->table);
		
		return $this->db->affected_rows();
	}
	
	function get_users($options = array()) {
		$options = $this->_default(array('sort_direction' => 'asc'), $options);
		
		$qualificationArray = array('email', 'status');
		foreach($qualificationArray as $qualifier) {
			if (isset($options[$qualifier]))
				$this->db->where($qualifier, $options[$qualifier]);
		}
		
		if (isset($options['limit']) && isset($options['offset']))
			$this->db->limit($options['limit'], $options['offset']);
			
		else if (isset($options['limit']))
			$this->db->limit($options['limit']);
			
		if (isset($options['sort_by']))
			$this->db->order_by($options['sort_by'], $options['sort_direction']);
			
		$query = $this->db->get($this->table);
		if ($query->num_rows() == 0)
			return false;
			
		if (isset($options['email'])) {
			return $query->row(0);
			
		} else {
			return $query->result();
		}
	}
	
	function delete_user($options = array()) {
		if(!$this->_required(array('email'), $options))
			return false;
			
		$this->db->where('email', $options['email']);
		$this->db->delete($this->table);
	}
	
	function _required($required, $data) {
		foreach($required as $field)
			if (!isset($data[$field]))
				return false;
		return true;
	}
	
	function _default($defaults, $options) {
		return array_merge($defaults, $options);
	}
}

Revision: 20378
at November 13, 2009 18:46 by Abe


Updated Code
/**
* AddUser method creates a record in the users table.
*
* Option: Values
* --------------
* userEmail         (required)
* userPassword
* userName
* userStatus        active(default), inactive, deleted
*
* @param array $options
*/
function AddUser($options = array())
{
    // required values
    if(!$this->_required(array('userEmail'), $options)) return false;
   
    // default values
    $options = $this->_default(array('userStatus' => 'active'), $options);
   
    // qualification (make sure that we're not allowing the site to insert data that it shouldn't)
    $qualificationArray = array('userEmail', 'userName', 'userStatus');
    foreach($qualificationArray as $qualifier)
    {
        if(isset($options[$qualifier])) $this->db->set($qualifier, $options[$qualifier]);
    }
   
    // MD5 the password if it is set
    if(isset($options['userPassword'])) $this->db->set('userPassword', md5($options['userPassword']));
   
    // Execute the query
    $this->db->insert('users');
   
    // Return the ID of the inserted row, or false if the row could not be inserted
    return $this->db->insert_id();
}

/**
* UpdateUser method alters a record in the users table.
*
* Option: Values
* --------------
* userId            the ID of the user record that will be updated
* userEmail
* userPassword
* userName
* userStatus        active(default), inactive, deleted
*
* @param array $options
* @return int affected_rows()
*/
function UpdateUser($options = array())
{
    // required values
    if(!$this->_required(array('userId'), $options)) return false;
   
    // qualification (make sure that we're not allowing the site to update data that it shouldn't)
    $qualificationArray = array('userEmail', 'userName', 'userStatus');
    foreach($qualificationArray as $qualifier)
    {
        if(isset($options[$qualifier])) $this->db->set($qualifier, $options[$qualifier]);
    }
   
    $this->db->where('userId', $options['userId']);
   
    // MD5 the password if it is set
    if(isset($options['userPassword'])) $this->db->set('userPassword', md5($options['userPassword']));
   
    // Execute the query
    $this->db->update('users');
   
    // Return the number of rows updated, or false if the row could not be inserted
    return $this->db->affected_rows();
}

/**
* GetUsers method returns an array of qualified user record objects
*
* Option: Values
* --------------
* userId
* userEmail
* userStatus
* limit             limits the number of returned records
* offset                how many records to bypass before returning a record (limit required)
* sortBy                determines which column the sort takes place
* sortDirection     (asc, desc) sort ascending or descending (sortBy required)
*
* Returns (array of objects)
* --------------------------
* userId
* userEmail
* userName
* userStatus
*
* @param array $options
* @return array result()
*/
function GetUsers($options = array())
{
    // default values
    $options = $this->_default(array('sortDirection' => 'asc'), $options);
   
    // Add where clauses to query
    $qualificationArray = array('userId', 'userEmail', 'userStatus');
    foreach($qualificationArray as $qualifier)
    {
        if(isset($options[$qualifier])) $this->db->where($qualifier, $options[$qualifier]);
    }
   
    // If limit / offset are declared (usually for pagination) then we need to take them into account
    if(isset($options['limit']) &amp;&amp; isset($options['offset'])) $this->db->limit($options['limit'], $options['offset']);
    else if(isset($options['limit'])) $this->db->limit($options['limit']);
   
    // sort
    if(isset($options['sortBy'])) $this->db->order_by($options['sortBy'], $options['sortDirection']);
   
    $query = $this->db->get('users');
    if($query->num_rows() == 0) return false;
   
    if(isset($options['userId']) &amp;&amp; isset($options['userEmail']))
    {
        // If we know that we're returning a singular record, then let's just return the object
        return $query->row(0);
    }
    else
    {
        // If we could be returning any number of records then we'll need to do so as an array of objects
        return $query->result();
    }
}

/**
* DeleteUser method removes a record from the users table
*
* @param array $options
*/
function DeleteUser($options = array())
{
    // required values
    if(!$this->_required(array('userId'), $options)) return false;
   
    $this->db->where('userId', $options['userId']);
    $this->db->delete('users');
}

/**
* _required method returns false if the $data array does not contain all of the keys assigned by the $required array.
*
* @param array $required
* @param array $data
* @return bool
*/
function _required($required, $data)
{
    foreach($required as $field) if(!isset($data[$field])) return false;
    return true;
}

/**
* AddUser method creates a record in the users table.
*
* Option: Values
* --------------
* userEmail         (required)
* userPassword
* userName
* userStatus        active(default), inactive, deleted
*
* @param array $options
*/
function AddUser($options = array())
{
    // required values
    if(!$this->_required(array('userEmail'), $options)) return false;
   
    // At this point we know that the key 'userEmail' exists in the $options array.
}

/*
$userId = $this->user_model->AddUser($_POST);

if($userId)
    echo "The user you have created has been added successfully with ID #" . $userId;
else
    echo "There was an error adding your user.";

if($this->user_model->UpdateUser(array('userId' => 3, 'userName' => 'Shawn', 'userEmail' => 'not telling')))
    // The user has been successfully updated
else
    // The user was not updated

$user = $this->user_model->GetUsers(array('userEmail' => $userEmail, 'userPassword' => md5($userPassword), 'userStatus' => 'active'));
if($user)
    // Log the user in
else
    // Sorry, your user / password combination isn't correct.

$users = $this->user_model->GetUsers(array('userStatus' => 'active'));

if($users)
{
    echo "Active Users<br />";
    foreach($users as $user)
    {
        echo $user->userName . "<br />";
    }
}
else
{
    echo "There are no active users.";
}

$this->user_model->DeleteUser(array('userId' => $userId));
*/

Revision: 20377
at November 13, 2009 18:43 by Abe


Initial Code
/**
* AddUser method creates a record in the users table.
*
* Option: Values
* --------------
* userEmail         (required)
* userPassword
* userName
* userStatus        active(default), inactive, deleted
*
* @param array $options
*/
function AddUser($options = array())
{
    // required values
    if(!$this->_required(array('userEmail'), $options)) return false;
   
    // default values
    $options = $this->_default(array('userStatus' => 'active'), $options);
   
    // qualification (make sure that we're not allowing the site to insert data that it shouldn't)
    $qualificationArray = array('userEmail', 'userName', 'userStatus');
    foreach($qualificationArray as $qualifier)
    {
        if(isset($options[$qualifier])) $this->db->set($qualifier, $options[$qualifier]);
    }
   
    // MD5 the password if it is set
    if(isset($options['userPassword'])) $this->db->set('userPassword', md5($options['userPassword']));
   
    // Execute the query
    $this->db->insert('users');
   
    // Return the ID of the inserted row, or false if the row could not be inserted
    return $this->db->insert_id();
}

/**
* UpdateUser method alters a record in the users table.
*
* Option: Values
* --------------
* userId            the ID of the user record that will be updated
* userEmail
* userPassword
* userName
* userStatus        active(default), inactive, deleted
*
* @param array $options
* @return int affected_rows()
*/
function UpdateUser($options = array())
{
    // required values
    if(!$this->_required(array('userId'), $options)) return false;
   
    // qualification (make sure that we're not allowing the site to update data that it shouldn't)
    $qualificationArray = array('userEmail', 'userName', 'userStatus');
    foreach($qualificationArray as $qualifier)
    {
        if(isset($options[$qualifier])) $this->db->set($qualifier, $options[$qualifier]);
    }
   
    $this->db->where('userId', $options['userId']);
   
    // MD5 the password if it is set
    if(isset($options['userPassword'])) $this->db->set('userPassword', md5($options['userPassword']));
   
    // Execute the query
    $this->db->update('users');
   
    // Return the number of rows updated, or false if the row could not be inserted
    return $this->db->affected_rows();
}

/**
* GetUsers method returns an array of qualified user record objects
*
* Option: Values
* --------------
* userId
* userEmail
* userStatus
* limit             limits the number of returned records
* offset                how many records to bypass before returning a record (limit required)
* sortBy                determines which column the sort takes place
* sortDirection     (asc, desc) sort ascending or descending (sortBy required)
*
* Returns (array of objects)
* --------------------------
* userId
* userEmail
* userName
* userStatus
*
* @param array $options
* @return array result()
*/
function GetUsers($options = array())
{
    // default values
    $options = $this->_default(array('sortDirection' => 'asc'), $options);
   
    // Add where clauses to query
    $qualificationArray = array('userId', 'userEmail', 'userStatus');
    foreach($qualificationArray as $qualifier)
    {
        if(isset($options[$qualifier])) $this->db->where($qualifier, $options[$qualifier]);
    }
   
    // If limit / offset are declared (usually for pagination) then we need to take them into account
    if(isset($options['limit']) &amp;&amp; isset($options['offset'])) $this->db->limit($options['limit'], $options['offset']);
    else if(isset($options['limit'])) $this->db->limit($options['limit']);
   
    // sort
    if(isset($options['sortBy'])) $this->db->order_by($options['sortBy'], $options['sortDirection']);
   
    $query = $this->db->get('users');
    if($query->num_rows() == 0) return false;
   
    if(isset($options['userId']) &amp;&amp; isset($options['userEmail']))
    {
        // If we know that we're returning a singular record, then let's just return the object
        return $query->row(0);
    }
    else
    {
        // If we could be returning any number of records then we'll need to do so as an array of objects
        return $query->result();
    }
}

/**
* DeleteUser method removes a record from the users table
*
* @param array $options
*/
function DeleteUser($options = array())
{
    // required values
    if(!$this->_required(array('userId'), $options)) return false;
   
    $this->db->where('userId', $options['userId']);
    $this->db->delete('users');
}

Initial URL
http://shawnmccool.com/2009/08/28/how-to-write-a-better-model-in-code-igniter/

Initial Description


Initial Title
How to Write a Better Model in CodeIgniter

Initial Tags
php, codeigniter

Initial Language
PHP