The following class holds an array with products that are generated from a Json file. This is what the json file looks like
[
{
"id": "A101",
"description": "Screwdriver",
"category": "1",
"price": "9.75"
},
{
"id": "A102",
"description": "Electric screwdriver",
"category": "1",
"price": "49.50"
},
{
"id": "B101",
"description": "Basic on-off switch",
"category": "2",
"price": "4.99"
}
]
I'm using a find method on a Product class, but I'm in doubt if storing all generated products in the class itself is a good idea
- Should I maybe create a ProductCollection class?
- Should I build my products[] collection differently then using my method
- Should I generate a Factory for the product creation from my Json file.
This is my code
class Product {
private static $products = [];
public static function initialize($url)
{
// Build the product from our JSON file
$data = json_decode(file_get_contents($url));
foreach($data as $item) {
$product = new Product();
$product->id = $item->id;
$product->description = $item->description;
$product->category = $item->category;
$product->price = $item->price;
self::$products[] = $product;
}
}
public static function find($id)
{
foreach(self::$products as $product) {
if($product->id == $id) {
return $product;
}
}
return false;
}
}
Thank you.