OOP, classes and databases [message #169408] |
Fri, 10 September 2010 13:18 |
Mattias Campe
Messages: 7 Registered: September 2010
Karma:
|
Junior Member |
|
|
Hello
I'm programming some classes that get their information from a MySQL
database. I started with mysql_query, function X () as constructor and
getValue and setValue.
I already found out that:
- PDO is better than mysql_query
- __construct is the way of making constructors
- __get and __set is the way for getting and setting properties
But I'm still kind of stuck with the 'best practices' with working
together with classes and databases. For now I have a class, let's say
'Person', that kind of works like this:
class Person {
private $name;
private $address;
public function __construct ($id,$db) {
$query = ... the select query ...
$row = $db->query($query);
foreach ($db->query($query) as $row) {
$this->name = $row['name'];
$this->address = $row['address'];
}
}
public function __get ($var) {
switch ($var) {
case 'Name':
return $this->name;
break;
case 'address':
return $this->address;
break;
default:
break;
}
}
}
But I have the feeling that this isn't a 'best practice':
- I can't use this class without database
- should I put the select query and getting the data in a seperate
function, outside the constructor?
- should I pass the database handler as a parameter or should I do it in
another way?
Would somebody happen to know a website that explains a little bit more
about OOP, classes and databases? I've already tried to do it myself,
but for now, I can't find the desired result.
Greetings
Mattias
|
|
|