我的应用程序涉及用户支付。在公司中,该用户具有以下状态:
如何在应用程序内部的多个地方(和规则)处理这些规则?
我是否需要一个像status_id
这样的字段和一个cron来每小时更新一次?
没有status_id
字段并在每个需要显示状态的查询中写入SQL规则?
加载User
模型并调用具有规则的->status()
方法?在这种情况下,我如何显示“总计”,例如:我们有3000个逾期用户,15000个不活跃的用户等等。
这让我头疼了好几个月,我真的需要帮助哈哈。我们目前有一个解决方案,但它太复杂,无法处理。由于在处理支付的应用程序中似乎很常见,所以必须有更简单的方法来做到这一点:P
谢谢!
Notes
发布于 2015-12-30 19:02:44
有趣的问题,但也不是一个单一的答案。
我认为这里的复杂性可能来自于周围的代码,而不是核心业务逻辑和需求。我这么说是因为三种状态类型都是从内部应用程序派生出来的,并不是太糟糕。
一种可能的解决方案,我假设某种级别的MVC或类似的。
考虑到您的模型,user
,并扩展了一个类似ORM的口才(我将从Laravel那里雄辩,因为我对它最熟悉,但任何ORM都会奏效):
use Illuminate\Database\Eloquent\Model;
use App\DebtCollector;
public class User extends Model
{
// Assuming model has the following fields
// id, status, registration_date, and a one to many
// relationship with debts
protected $fillable = [
'raw_status',
'registration_date',
];
public function debts()
{
return $this->hasMany(Debt::class);
}
public function refreshStatus()
{
$dc = new DebtCollector();
// Business logic inside the "DebtCollector" class
$this->raw_status = $dc->resolveStatus($this->debts, $this->registration_date);
// Save value to the underlying datebase
$this->save();
}
// If you fetch a status directly, it will refresh first,
// then return the value
//
public function getStatusAttribute()
{
$this->refreshStatus();
return $this->raw_status;
}
}
// Schedule task somewhere - ran nightly, or whenever
//
// This way you can refresh the status only on certain groups
// of data - for example, if the business flow means that once
// they become compliant, they can't go back, there is no need
// to refresh their status anymore
//
User::where('raw_status', '<>', 'compliant')->refreshStatus();
// Alternatively, the schedule could chunk results and do an update
// only to those not updated in the last 24 hours
//
$date = new DateTime;
$date->modify('-24 hours');
$formatted_date = $date->format('Y-m-d H:i:s');
User::where('last_updated', '>', $formatted_data)->refreshStatus();
发布于 2015-12-30 18:29:07
如果您在多个地方使用这个字段,那么您应该将状态存储在一个地方并酌情更新它(我也会保存状态的历史记录,但这是另一回事)。
如果状态由于某些用户操作(例如正在处理的支付)而发生变化,则可以在操作上使用触发器。但是,您的状态更改似乎是基于事件发生后的时间变化。在这种情况下,您应该运行一个定期调度的作业(作为cron作业或数据库事件)。
我有点搞不懂你为什么每小时都这么做。看来每天一次是最合适的。如果“债务”是在任意时间支付的,则支付过程应更新状态。对于降级状态,一天一次的工作就足够了。
发布于 2016-01-02 08:10:06
我想说,这个问题有多种解决办法。
我建议不要有任何明确的地位。根据我所看到的,您可以根据其他一些数据“确定”当前的状态。例如,“到目前为止,用户已经还清了所有债务”。你只需通过分析给定时期内的所有变化就可以知道这一点。您可以聚合数据以确定您需要知道的所有信息。所以你根本不需要保存状态。它只是从客户帐户在特定时期发生的所有更改中派生出来的。
总数也是一样。您可以在数据库级别上很容易地做到这一点,甚至可以使用一些基于文档的DB或ElasticSearch。
当然,这假定您跟踪更改的历史。如果你这么做-问题解决了。如果没有-您必须将状态保存到数据库中,并且无法获得历史数据。
https://stackoverflow.com/questions/34540135
复制相似问题