I have a problem with my Lavavel controller, my controller is waiting for the productRequest sent from a form which contains a value names 'productType', then i use that value to decide which object need to be created (I had 3 classes extended from the Product class).
public function store(ProductRequest $request){
if ($request['productType'] == '0'){
$disk = new Disk($request->all());
$disk->save();
}
elseif ($request['productType'] == '1'){
$book = new Book($request->all());
$book->save();
}
else{
$furniture = new Furniture($request->all());
$furniture->save();
}
}
So my question is that Is there any other way to get this task done or any functions that helps create the object with the parameter of productType ?
CodePudding user response:
I'm not a super OOP guy but for fun; so long as they take the same argument and call the same method(s) you can use an array keyed to the productType
with the class name:
$types = ['Disk', 'Book', 'Furniture'];
$type = $types[$request['productType']];
${$type} = new $type($request->all());
${$type}->save();
Actually you don't need the variable object if you can use the same variable name. Just use $product
for all:
$product = new $type($request->all());
$product->save();
Or to have it default to Furniture
if not defined:
$types = ['Disk', 'Book'];
$type = $types[$request['productType']] ?? 'Furniture';
You may want to define the keys to avoid ambiguity and in case there are gaps:
$types = [0 => 'Disk', 1 => 'Book', 2 => 'Furniture'];
Another alternative would be a switch
, or maybe a hybrid of the two depending on your needs:
switch($request['productType']) {
case '0':
$disk = new Disk($request->all());
$disk->save();
break;
case '1':
$book = new Book($request->all());
$book->save();
break;
case '2':
$furniture = new Furniture($request->all());
$furniture->save();
break;
}
Or use default:
instead of case '2'
.