Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using models in CodeIgniter

Can somebody explain to me when it's a good practice to use models in CI? An article in wikipedia was referring to CI models as "entirely optional and are rarely needed" is that true in any way?

like image 963
rabidmachine9 Avatar asked Nov 29 '22 18:11

rabidmachine9


2 Answers

Say you needed to call a function called get_user_info that retrieves the users info from a database. You could have a function like this:

class Home extends Controller {

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

    function index() {
        $user = $this->get_user_info($_SESSION['user_id']);
        echo "Hello " . $user['first_name'];
    }

    function get_user_info($user_id) {
        $query = $this->db->query("SELECT * FROM users WHERE user_id = ?", array($user_id));
        return $query->row_array();
    }
}

However, what if you needed to call get_user_info on another page?

In this scenario you would have to copy and paste the function into every page making it difficult to maintain if you have lots of pages (what if you needed to change the query to JOIN onto another table?)

This also goes against the don't repeat yourself principle.

Models are meant to handle all data logic and representation, returning data already to be loaded into views. Most commonly they are used as a way of grouping database functions together making it easier for you to change them without modifying all of your controllers.

class User extends Model {

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

    function get_user_info($user_id) {
        $query = $this->db->query("SELECT * FROM users WHERE user_id = ?", array($user_id));
        return $query->row_array();
    }

}

In the above we have now created a model called user. In our home controller we can now change the code to read:

class Home extends Controller {

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

    function index() {
        $this->load->model('user');
        $user = $this->user->get_user_info($_SESSION['user_id']);
        echo "Hello " . $user['first_name'];
    }
}

And now you can change your get_user_info function without having to change X number of controllers that rely on the same function.

like image 112
fire Avatar answered Dec 04 '22 09:12

fire


No!! That's not true. Models are used as a layer between your controller and the database. MVC best practice is a subjective matter at best. People use it in different ways. A framework like CodeIgniter is great because it allows that level of flexibility. Other frameworks are much more strict. I'm general I try and keep my controllers very small and specific and put lots of code (db interaction and parsing results etc) in a model.

like image 28
musoNic80 Avatar answered Dec 04 '22 10:12

musoNic80