There is a base class Product
having all the generic properties and methods which a product should have.
abstract class Product
{
public abstract function process();
}
Now, These are the few types of products which may or may not have similar logic.
class Shirt extends Product
{
public function process()
{
return 0;
}
}
class Trouser extends Product
{
public function process()
{
return 1;
}
}
class PocketSquare extends Product
{
public function process()
{
return 2;
}
}
I've used switch statement to distinguish and initialise objects.
$products = $db->query("SELECT * FROM products LIMIT 10");
foreach ($products as $key => $product) {
switch ($product->type) {
case 'shirt':
$products[$key] = new Shirt($product);
break;
case 'trouser':
$products[$key] = new Trouser($product);
break;
case 'pocketsquare':
$products[$key] = new PocketSquare($product);
break;
}
}
Is there any way to avoid switch statement? or any better approach?