Re: OOP, classes and databases [message #169436 is a reply to message #169408] |
Mon, 13 September 2010 06:41 |
alvaro.NOSPAMTHANX
Messages: 277 Registered: September 2010
Karma:
|
Senior Member |
|
|
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']);
}
> - should I pass the database handler as a parameter or should I do it in
> another way?
When I've done it that way I've found it quite practical.
--
-- http://alvaro.es - Álvaro G. Vicario - Burgos, Spain
-- Mi sitio sobre programación web: http://borrame.com
-- Mi web de humor satinado: http://www.demogracia.com
--
|
|
|