Database Objects Question

If I have a basic database class, is this (below) the proper way to create a database object in other classes? IE. Should I create an instance in the construct and then will it be available elsewhere?

Also, how would I call the below in usage? Would I just be able to create the MyClass object or do I have to create a Database object first?

Thanks in advance for any helps (I’m relatively new with classes that aren’t built for me with frameworks!).


class MyClass {
	private $db;
	
	function __construct() {
		$this->db = new Database();
	}

	function createSomething($attribute) {
		$this->db->query("INSERT INTO something (attribute) VALUES $attribute");
	}

}

I normally do something like this:


class MyClass extends Database { 
    
    function __construct() { 
        parent::__construct();
    } 

    function createSomething($sql) { 
        return $this->query($sql); 
    }
} 
$obj = new MyClass;
$obj->createSomething("INSERT INTO tblename(field1,field2) VALUES('$val1', '$val2')");

Thank you for the help!

Extending sounds like a better way to do it…

I have it in a more generic way:


# main class
abstract class DTO {
  public $primaryKey = null; # holds the pk
  protected $_data = array(); # holds the data to be changed / get from db

  public function __constructor($id = null) {
    if ($id) {
      $this->_data = DB::selectRow("SELECT * FROM " . get_called_class() . " WHERE id = '".$id."'");
      $this->primaryKey = $id;
    }
  }

  public function save() {
    $values = array();
    foreach ($this->_data as $key => $value) {
      $values[] = $key . " = '" . $value . "'"; # escape this if need be
    }
    if ($this->primaryKey !== null) {
      DB::update("UPDATE " . get_called_class() . " SET " . join(', ', $values) . " WHERE id = '".$this->primaryKey."'");
    } else {
      DB::insert("INSERT INTO " . get_called_class() . " SET " . join(', ', $values) );
    }
  }

  public function __set($key, $value) {
    $this->_data[$key] = $value;
  }

  public function __get($key) {
    return $this->_data($key);
  }
}

# Models / DTOs / whatever you want to call em
class User extends DTO {

}

class Foo extends DTO {

}

# Usage
$user = new User();
$user->name = 'bob';
$user->age = 15;
$user->save(); # INSERT INTO user SET name = 'bob', age = '15';

$otherUser = new User(5); # SELECT * FROM user WHERE id = 5;
$otherUser->name = 'not bob';
$otherUser->save(); # UPDATE user SET name = 'not bob' WHERE id = '5';

That way, I almost never have to write any SQL.

i do almost similar but instead of it in php >5.3 i make those function static so that function sticks around through we dont have object (created) which eases task in many situation.
plus i was having problem earlier in date_time function because of ‘NOW()’ in the generic insert function which i solved later…