I have a factory called ProductFactory
I can create a product like so:
$product = ProductFactory::getProduct($id);
Now depending on what type of product we are getting, this function may return a class of type Product
or a descendant or Product
.
But using the method above, the $product
class would be responsible for connecting to the database and retrieving its data.
So if I were to select 20 products to be displayed on a category list, I would have to first get a list of all the ID's then call the above function 20 times. This would be 21 calls to the database.
So I added another function to my factory like so:
$product = ProductFactory::createProduct($data);
This does the same thing, except you pass in the data from the database, saving the $product
class from having to make the trip. (depending on what data you pass, the factory will return the right type of class).
So now I want to make one call to select all products data and FETCH_INTO
my factory to generate a $product object for each row.
How can I do that?
update
Here is what I tried that did not work:
$stmt->setFetchMode(PDO::FETCH_INTO,ProductFactory::createProduct);
foreach($stmt as $product)
{
echo get_class($product) . '<br>';
}