masphp
masphp

Reputation: 3

codeigniter mvc , model separation

Here is my problem in codeigniter MVC.

Suppose I have 3 models: (users, email , payments). When some one paid by some way , controller calls some method of payments model , that method could be called from other controllers too.

That method , does some database insert and update and at the end , it wants to send an email to user , it already has userid , but it needs username , email , which should get from users table and then send email.

I don't like payments model could have access to users table and I want to get info from users model and send email using email model.

normally I call those from controller , I mean first call payments model and get the result and get users info from users model and then use email model , all in controller .

But because I need to run that model's method in some controllers , I must repeat those lines and it is not the correct aspect in my point.

Question: Should I call other models inside model or use other models tables inside model (in this option , if I want to reuse that model I should change it if other tables changed which is not right) , or is there any other way?

The main problem is not exactly that one it is just example of situation . I also defined some function which does those thing and call from controllers , but it is not right too.

Upvotes: 0

Views: 280

Answers (2)

Muhammad Raheel
Muhammad Raheel

Reputation: 19882

Here is a great solution. Define My_model.php in application/core.

Class My_model extends CI_Model{

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

    function get($where , $table){
        $query = $this->db->get_where($table, $where);
        return $query->result();
    }
}

Now you model should extend My_model instead of CI_Model. And now you can call it like this. Let suppose in your controller you have loaded email model and you want to access user model.

 $where = array('user_id', $id); 
 $table = 'user';
 $this->email->get($table, $where);

For more information read this book
http://codeigniter.com/forums/viewthread/211821/

Upvotes: 1

Laurence
Laurence

Reputation: 60068

Put it all into a library.

So your controller calls the library for a "payment", and passes some details. Your library then does ALL of the features you describe above - i.e. calls the payment model, sends the email etc etc.

You can learn more about codeigniter libraries here

Upvotes: 1

Related Questions