I have a quick one: I'm a beginner with PHP Object, and I have a product table with all my products.
I also have a class for my product (with a constructor that fills my instance with all the parameters of my product).
Say I want a list of all my product, shall I create a separate class for my list of products, or create a function that creates a new instance of my product class ?
I don't really get the benefits of it right now, because if I have to execute the exact same query as my class query, it's useless ?
Thank's for your tips !
UPDATE
Thank's folks ! It's still quite complicated for me, but here's what I did (talking about books) trying to follow your advices.
I created a DAO. Inside this DAO, I have two static functions that return me either a list of books or a single book, and one static that creates the book object.
With this method, I still have 2 queries (one for the list, one for the single book). I have a feeling this is wrong but any help is appreciated :)
class bookDAO {
public static function getBooks() {
$books = array();
$db = databaseConnection::getInstance();
$query = $db->query("SELECT * FROM books");
while($row = $query->fetchObject()) {
$book = self::createBookFromRow($row);
$books[] = $book;
}
return $books;
}
public static function getBook($id){
$db = databaseConnection::getInstance();
$query = $db->prepare("SELECT * FROM books WHERE id=:id");
$query->execute(array(":id"=>$id));
$row = $query->fetchObject();
$book = self::createBookFromRow($row);
return $book;
}
private static function createBookFromRow($row) {
$book = new book($row);
return $book;
}
}