问题描述
我使用此自定义类代码在Laravel中处理不同类型的订单。该问题包括有关订单类型A的代码。
我想知道如何在对象创建中重用代码。因为我在代码中看到很多重复。
我具有功能相同但行为不同的不同订单类型。这就是为什么我使用抽象类扩展所有订单类型的原因。
abstract class BaSEOrder
{
abstract public function getorder(Order $order);
abstract public function storeOrder(Request $request);
...
}
class OrderTypeA extends BaSEOrder
{
private $type = 'A';
public function storeOrder($request)
{
$returnedValues = DB::transaction(function () use ($request) {
$order = new Order;
$order->type = $this->type;
$order->from = $request->json('from');
$order->amount = $request->json('amount');
$order->status = 2;
$order->save();
foreach ($request->json('items') as $item) {
$order->items()->create([
'product_id' => $item['product_id'],'quantity' => $item['quantity'],'total' => $item['total'],]);
}
return compact('order');
});
return $returnedValues['order']->load('items');
}
public function updateOrder($request)
{
$returnedValues = DB::transaction(function () use ($request) {
if ($request->id) {
$order = Order::findOrFail($request->id);
$order->amount = $request->json('amount');
$order->status = 1;
$order->save();
$order->items()->delete();
foreach ($request->json('items') as $item) {
$order->items()->create([
'product_id' => $item['product_id'],]);
}
} else {
$order = new Order;
$order->type = $this->type;
$order->from = $request->json('from');
$order->to = null;
$order->amount = $request->json('amount');
$order->status = 1;
$order->save();
foreach ($request->json('items') as $item) {
$order->items()->create([
'product_id' => $item['product_id'],]);
}
}
return compact('order');
});
return $returnedValues['order']->load('items');
}
public function generateOrder($customer)
{
$order = new stdClass();
$order->id = null;
$order->type = $this->type;
$order->from = $customer->id;
$order->to = null;
$order->status = 1;
$totalAmount = 0;
$items = [];
$stocks = Stock::where('type',1)
->where('customer_id',$customer->id)
->whereRaw('stock <= reorder_level')
->get();
if (count($stocks) > 0) {
foreach ($stocks as $key => $stock) {
if ($stock->minimum_order_quantity != 0) {
$priceListItem = PriceList::where('product_id',$stock->product_id)->latest()->first();
$item = new stdClass;
$item->id = $key;
$item->product_id = $stock->product_id;
$item->product = Product::findOrFail($stock->product_id);
$item->order_id = null;
$item->quantity = (int) $stock->minimum_order_quantity;
$item->total = ((int) $stock->minimum_order_quantity * ((float) $priceListItem->price));
$item->is_checked = true;
$item->created_at = null;
$item->updated_at = null;
$totalAmount += $item->total;
$items[] = $item;
}
}
}
$order->amount = $totalAmount;
$order->items = $items;
return $order;
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)