Re: OOP, classes and databases [message #169473 is a reply to message #169436] |
Tue, 14 September 2010 18:56 |
Mattias Campe
Messages: 7 Registered: September 2010
Karma:
|
Junior Member |
|
|
Op 13-09-10 08:41, "Álvaro G. Vicario" schreef:
> El 10/09/2010 15:18, Mattias Campe escribió/wrote:
>> 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'];
>> }
>> }
> [...]
>> 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?
>
> You are right about this gotcha. One approach is to make your
> constructor and most other methods DB agnostic:
>
> public function __construct($id, $name, $address){
> // ...
> }
>
> ... and then build a set of static methods to perform database reads:
>
> public static function getById(PDO $db, $id){
> // ....
> return new Person($row['id'], $row['name'], $row['adress']);
> }
How could I use this class? Because I would need to make a Person from
the database, but first I would need to make a "random" Person, like:
$oPerson = new Person("000","something that will be overwritten","blabla");
$oPerson->getById($dbh,"245");
But I think that I'm not getting the picture right....
Greetings
Mattias
|
|
|