Welcome Guest, Not a member yet? Register   Sign In
Best practice of saving to database within custom class
#1

(This post was last modified: 09-29-2019, 03:57 PM by adampwe.)

Previously, whenever I was getting anything out of the database I was using 'result_array()', so the data is returned within an array, and when I wanted to amend the data within the array, I had a function within the model to update the field. But it becomes difficult to make sure the array data is always in a format I expect. e.g. 'Undefined index: new_field' errors

E.G. 

PHP Code:
class user_model extends CI_Model {

  public function get_user($id) {
      $this->db->where('id'$id);
      return $this->db->get($table)->result_array();
  }

  public function update_username($id$name) {
      $this->db->where('id'$id);
      $this->db->update($table, array('name' => $name));
  }





Now, I want to utilize classes, so I have a 'user' class, which means I can have custom functions for business logic etc.

  
PHP Code:
class user_model extends CI_Model {

   public function get_user($id) {
      $this->db->where('id'$id);
      return $this->db->get($table)->custom_result_object('user');
   }

}

class 
user {

   public function get_name() : string {
      return trim($this->name);
   }

   public function set_name($new_name) : void {
      /* WHAT TO DO HERE */
   }

   public function Foo() : void {
     
   
}





I'm unsure on what's the best solution for set_name. Should I just set the local variable e.g. '$this->name = $new_name' then have another function called 'save()' which goes to the database and actually saves the data? Or is another solution best?

Any help would be greatly appreciated.

Thanks,
Adam
Reply




Theme © iAndrew 2016 - Forum software by © MyBB