I have an order model and a client model. A client has many orders, an order belongs to a single client.
In the client model I keep track of how much money a client paid (total_generated_revenue
), how many orders he has cancelled (orders_cancelled
), and how many of his orders were completed (orders_got
).
In the order model I have a status attribute and a total attribute (and the client_id
attribute, of course).
When status of an order changes, I change other properties of the object with respect to the exact change that happened in status. Actions on each change are different. Status can either be 0, 1, or 2, so there are 6 possible changes in status. I handle this with 7 if
statements:
public function updated(Order $order)
{
$unchanged_order = $order->getOriginal();
if($unchanged_order->status == $order->status)
{
// skip if status wasn't changed. I use this skip so that we don't have to check all of the following.
}
elseif($unchanged_order->status == 0 && $order->status == 1)
{
$order->client->total_generated_revenue += $order->total;
$order->client->orders_got += 1;
}
elseif($unchanged_order->status == 0 && $order->status == 2)
{
$order->client->orders_cancelled += 1;
}
elseif($unchanged_order->status == 1 && $order->status == 2)
{
$order->client->total_generated_revenue -= $order->total;
$order->client->orders_got -= 1;
$order->client->orders_cancelled += 1;
}
elseif($unchanged_order->status == 1 && $order->status == 0)
{
$order->client->total_generated_revenue -= $order->total;
$order->client->orders_got -= 1;
}
elseif($unchanged_order->status == 2 && $order->status == 1)
{
$order->client->total_generated_revenue += $order->total;
$order->client->orders_got += 1;
$order->client->orders_cancelled -= 1;
}
elseif($unchanged_order->status == 2 && $order->status == 0)
{
$order->client->orders_cancelled -= 1;
}
$order->client->save();
}
Is it considered a bad practice? If so, how can I refactor this code?
Does the name $unchanged_order
reflect well enough that I mean the version before change? Should I rename it into $order_before_change
?
0
,1
, and2
mean within your application? \$\endgroup\$