Welcome Guest, Not a member yet? Register   Sign In
Using Custom Libraries with Model instances.
#1

(This post was last modified: 08-24-2018, 11:57 PM by deltatangodt. Edit Reason: adding more data )

Hello, trying to understand the best way to have multiple instances of a class with its own Model "instance" & CI capability.

As an example, let's say I am handling a transaction between 2 users who interact, and I want to load/create 2 instances of a User class where each has methods to update their records.

Would a library be the best way to do this? What I am thinking is:

/libraries/User.php


PHP Code:
class User{

  private $CI;
  private $data;
  private $id;

  public function __construct($userid){
     $this->CI =& get_instance();
     $this->CI->load->model('user_model');
     $this->data = $this->user_model->get_user_data($userid);
     if($this->data)
     {
        $this->id $userid;
        return 
$this->data;
     }
     else
     {
        return 
false;
     }
  }

  public function 
set($field,$value){
    
$this->data->$field $value;
  }

  public function 
save(){
    return 
$this->user_model->update_user($this->id,$this->data);
  }
  



Then, in my controller, I am thinking of doing:

PHP Code:
$sender = new User($senderId);
$recipient = new User($recipientId);

$sender->set('name','Thomas Smith');
$sender->set('location','Los Angeles');
$sender->save();

$recipient->set('name','Peter Jones');
$recipient->set('location','London');
$recipient->save(); 

After reading the documentation and thinking this over, it seems to be the best way but want to make sure.
Reply
#2

(This post was last modified: 08-26-2018, 06:07 AM by deltatangodt.)

So delving more into the documentation and looking all over the internet there seems to be a couple ways to do this.

I am documenting it for future users:

1. If I do the above code [creating a library], I need to actually then load it in my controller like so:

$this->load->library('User',array('id'=>$senderId),"sender");
$this->load->library('User',array('id'=>$recipientId),"recipient");

And then do:

$this->sender->set('name','Thomas Smith');
$this->sender->set('location','Los Angeles');
$this->sender->save();

$this->recipient->set('name','Peter Jones');
$this->recipient->set('location','London');
$this->recipient->save();

OR, you could probably do (in your controller):

$this->load->library('User',array('id'=>$senderId),"sender");
$this->load->library('User',array('id'=>$recipientId),"recipient");

$sender =& $this->sender;
$recipient =& $this->recipient;

And then use them in your code as:

$sender->set('name','Thomas Smith');
$sender->set('location','Los Angeles');
$sender->save();

$recipient->set('name','Peter Jones');
$recipient->set('location','London');
$recipient->save();

---
Reply




Theme © iAndrew 2016 - Forum software by © MyBB