本次优化对 LotteryChanceService
进行了全面的重构和优化,提升了代码质量、性能、可维护性和可扩展性。
const DEFAULT_BATCH_SIZE = 100;
const MAX_BATCH_SIZE = 1000;
const TRIGGER_TYPE_ORDER = 'order';
const TRIGGER_TYPE_RECHARGE = 'recharge';
const TRIGGER_TYPE_ACCUMULATE = 'accumulate';
const TRIGGER_TYPE_MANUAL = 'manual';
if (empty($orderInfo) || empty($userId)) {
throw new Exception('订单信息或用户ID不能为空');
}
trace("抽奖机会分发失败 - 活动ID: {$activity->id}, 用户ID: {$userId}, 错误: " . $e->getMessage(), 'error');
public static function batchInitChances($activityId, $userIds, $initChances = 1, $batchSize = null)
{
$batchSize = $batchSize ?: static::DEFAULT_BATCH_SIZE;
$batchSize = min($batchSize, static::MAX_BATCH_SIZE);
// 分批处理逻辑
}
manualGrantChance()
- 手动给用户增加抽奖机会batchInitChances()
- 批量初始化用户抽奖机会batchCheckUserQualification()
- 批量检查用户资格batchValidateConditionsForUsers()
- 批量验证条件getUserAllChancesOverview()
- 获取用户所有活动机会概览getActivityParticipationStats()
- 获取活动参与统计// 管理员手动给用户增加抽奖机会
LotteryChanceService::manualGrantChance($activityId, $userId, $chances, $reason, $adminId);
// 批量初始化用户抽奖机会
$result = LotteryChanceService::batchInitChances($activityId, $userIds, $initChances, $batchSize);
// 获取活动参与统计
$stats = LotteryChanceService::getActivityParticipationStats($activityId);
// 获取用户所有活动机会概览
$overview = LotteryChanceService::getUserAllChancesOverview($userId);
$orderInfo = [
'id' => 123,
'total_amount' => 100.00,
'goods' => [
['goods_id' => 1],
['goods_id' => 2]
]
];
$grantedChances = LotteryChanceService::checkAndGrantChanceForOrder($orderInfo, $userId);
$rechargeInfo = [
'amount' => 50.00,
'type' => 'recharge'
];
$grantedChances = LotteryChanceService::checkAndGrantChanceForRecharge($rechargeInfo, $userId);
$success = LotteryChanceService::manualGrantChance(
$activityId,
$userId,
5,
'补偿用户',
$adminId
);
$userIds = [1, 2, 3, 4, 5];
$result = LotteryChanceService::batchInitChances($activityId, $userIds, 1, 100);
$chanceDetail = LotteryChanceService::getUserChanceDetail($activityId, $userId);
本次优化显著提升了 LotteryChanceService
的代码质量、性能和可维护性。通过引入新的功能特性、优化现有逻辑、完善错误处理和文档,使得该服务类更加健壮、高效和易于使用。这些改进为抽奖系统的稳定运行和后续扩展奠定了坚实的基础。