Object Oriented Approach in Codeigniter Model

Troy picture Troy · Jan 16, 2014 · Viewed 10.6k times · Source

I have been wondering what is the right way to write code in OO style in model. Certainly you can have a function that retrieve data from DB and then map to model-level variables. This approach, however, becomes counterintuitive when you have other function in model trying to get other data from BD. For example:

class User extends CI_Model {
    $id, $name, $age .... ;

    public function get_user_from_db_with_id($id) {
        ...
        // get data and map to variable. 
    } 

    public function get_all_users() {
    // return all users in db
    }

}

somewhere in controller:

$user = new User();
$ben = $user->get_user_from_db_with_id($id);

// this does not make sense!! 
$all_user = $ben->get_all_users();

Any thought or comment?

Thanks in advance!

Answer

Dazz Knowles picture Dazz Knowles · Jan 19, 2014

I had to make a similar decision and opted for this (trimmed for clarity)

class UserModel extends MY_Model 
{

    public $UserID = 0;
    public $CustomerID = null;
    public $FirstName = '';
    public $LastName = '';
    public $EmailAddress = '';
    public $Password = null;
    public $UserGroupID = true;     

    function __construct()
    {
        parent::__construct();
    }

    private function get($id)
    {
        $row = $this->get($id);
        if ($row !== null)
        {
            $this->dbResultToObject($row, $this);
        }
    }

    // Return an array of User objects
    public function get_list($deleted = false, $userIDToInclude = null) 
    {
        $params = array(null, $deleted, $userIDToInclude);
        $query = $this->db->call("spUserGet", $params);

        $users = array();
        foreach ($query->result() as $row)
        {
            $user = new UserModel();
            $this->dbResultToObject($row, $user);
            $users[] = $user; 
        }

        return $users;        
    }

    // Other Methods (Validate, Save etc)
}

I use a mixture of public, protected and private properties so that the reflection code I've written to map the properties from the DB results and to the DB sproc calls then only includes the public properties and prevents too many parameters being sent. But that's getting off-topic so my controller then just looks like:

class Users extends MY_Controller 
{

    public function __construct()
    {
        parent::__construct();
        $this->load->model('UserModel', 'user');
    }

    ....

}

Then a list can be retrieved with

$users = $this->user->get_list();

And a single record with

$user = $this->user->get($userID);