1.为什么要有状态机?状态机又是什么?
有些订单的状态,任务的状态过于复杂,状态机是为了方便我们管理整个任务,订单的状态,防止错误的状态切换。毕竟现在都是团队合作。有一个模型来管理,也好规范其它程序员代码质量。
2.订单状态机
namespace app\api\service;
class OrderService
{
//订单状态可以考虑成int 类型,mysql检索速度快
public static $STATUS_NEW = 'new'; //新订单
public static $STATUS_PAYED = 'payed'; //已支付
public static $STATUS_DELIVERY = 'delivery'; //已发货
public static $STATUS_RECEIVED = 'received'; //收货
public static $STATUS_COMPLETE = 'complete'; //已完成
private static $ALLOW_CHANGE_STATUS = [
'new' => ['payed'],
'payed' => ['delivery'],
'received' => ['received'],
'delivery' => ['complete'],
];
/**
* 状态切换
* @param $status
* @param $data
* @throws \Exception
*/
public function changeStu($status, $data)
{
//check order status
$order=Order::find($data['orderNo']);
if(!in_array($status,self::$ALLOW_CHANGE_STATUS[$order['status']])){
throw new \Exception(' order status error');
}
}
/**
* 订单管理
* @param $status
* @param $data
* @return bool|void
*/
public function dispatch($status, $data)
{
$result = false;
switch ($status) {
case self::$STATUS_NEW:
$result = self::createNew($data);
break;
case self::$STATUS_PAYED:
$result = self::payed($data);
break;
case self::$STATUS_DELIVERY:
$result = self::delivery($data);
break;
case self::$STATUS_RECEIVED:
$result = self::received($data);
break;
case self::$STATUS_COMPLETE:
$result = self::complete($data);
break;
default:
$result = false;
}
return $result;
}
//各自功能实现
private static function createNew($data)
{
//create new order
}
private static function payed($data)
{
//make the order payed
}
private static function delivery($data)
{
//make the order delivery
}
private static function received($data)
{
//make the order reveived
}
private static function complete($data)
{
//make the order complete
}
}