Reputation: 4204
I've created a User database abstraction class in PHP which extends a base class I made called DBO (database object). The DBO object's job is just to hold $db
as my codeigniter's $db
reference.
So ideally, in my User object, I could do $this->db->insert()
and access my codeigniter's database object.
here's my code:
DBO:
class DBO {
public $db;
public $ci;
//put your code here
public function __construct() {
$ci =& get_instance();
$this->db =& $ci->db;
}
}
USER: (which extends DBO)
class User extends DBO{
/** User id of the user
* @var int */
public $user_id;
/** User's first name in english
* @var string */
public $first_name;
/** User's last name in english
* @var string */
public $last_name;
/** User's name in Korean
* @var string */
public $korean_name;
/** User's phone number
* @var string */
public $phone;
/** User's email address
* @var string */
public $email;
/**
* Creates a new user from a row or blank.
* Creates a new user from a database row if given or an empty User object if null
*
* @param Object $row A row object from table: admin_users
*/
public function __construct(stdClass $row = null){
if($row){
if(isset($row->user_id)) $this->user_id = $row->user_id;
if(isset($row->first_name)) $this->first_name = $row->first_name;
if(isset($row->last_name)) $this->last_name = $row->last_name;
if(isset($row->korean_name)) $this->korean_name = $row->korean_name;
if(isset($row->phone)) $this->phone = $row->phone;
if(isset($row->email)) $this->email = $row->email;
}
}
/**
* Saves this user to the database.
* @return boolean Whether this was successfully saved to the database.
*/
public function create(){
$data = array(
'first_name' => $this->first_name,
'last_name' => $this->last_name,
'korean_name' => $this->korean_name,
'phone' => $this->phone,
'email' => $this->email,
);
if($this->db->insert(Tables::$USERS, $data) && $this->db->affected_rows() == 1){
$this->user_id = $this->db->insert_id();
return true;
} else {
return false;
}
}
But whenever I try to use $this->db->insert()
, it says Call to a member function insert() on a non-object.
Is there a way to make this work? Or is it fundamentally wrong? Should my User class ONLY hold the information, and pass a User object to my Users model object and have that run the database functionality?
Thanks for the help
Upvotes: 0
Views: 211
Reputation: 5202
You are missing call to the parent constructor. Use
parent::__contstruct()
in your user class constructor. By doing this, the parent class constructor will be called and so the db object will be initialised and you will be able to use it.
You should also read this
http://www.techflirt.com/tutorials/oop-in-php/inheritance-in-php.html
to understand inheritance. Kindly read about OOPs also so you can get idea of features OOPs in PHP is providing.
Upvotes: 2