mohammedmanssour/laravel-recurring-models

为Laravel模型添加可重复功能

v0.7.0 2024-05-10 20:03 UTC

README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

介绍我们的Laravel Recurring包 - 为Laravel模型添加可重复功能的终极解决方案!无论您需要简单的每天、每周或每n天重复,还是更复杂的模式,如每月第二个星期五重复模型,我们的包都能满足您的需求。通过无缝集成到您的Laravel应用程序中,您可以使用几行代码轻松管理和自动化重复任务。

安装

您可以通过composer安装此包

composer require mohammedmanssour/laravel-recurring-models

您可以使用以下命令发布和运行迁移

php artisan vendor:publish --tag="recurring-models-migrations"
php artisan migrate

用法

为模型添加可重复功能

  1. 确保您的模型实现了Repeatable契约。
use MohammedManssour\LaravelRecurringModels\Contracts\Repeatable as RepeatableContract;

class Task extends Model implements RepeatableContract
{

}
  1. Repeatable特质添加到您的模型中
use MohammedManssour\LaravelRecurringModels\Contracts\Repeatable as RepeatableContract;
use MohammedManssour\LaravelRecurringModels\Concerns\Repeatable;

class Task extends Model implements RepeatableContract
{
    use Repeatable;
}
  1. 可选,自定义模型基准日期。
/**
 * define the base date that we would use to calculate repetition start_at
 */
public function repetitionBaseDate(RepetitionType $type = null): Carbon
{
    return $this->created_at;
}

模型可重复规则

Repeatable特质有一个repeat方法,可以帮助您为模型定义可重复性规则。

repeat方法将返回一个具有4个方法的Repeat辅助类:dailyeveryNDaysweeklycomplex

1. 每日重复

这可以帮助您为模型创建每日重复规则。

$model->repeat()->daily()

重复将从基于返回值的repetitionBaseDate的下一天开始。

2. 每 N 天重复

这可以帮助您为模型创建每 N 天的重复规则。

$model->repeat()->everyNDays(days: 3)

重复将在 n=3 天后基于返回值的repetitionBaseDate开始。

3. 每周重复

这可以帮助您为模型创建每周重复规则。

$model->repeat()->weekly()

重复将在基于返回值的repetitionBaseDate的7天后开始。

您可以使用on方法指定重复的日期。

$model->repeat()->weekly()->on(['sunday', 'monday', 'tuesday'])

4. 复杂重复。

这可以帮助您创建任务的复杂重复规则。

$model->repeat()
    ->complex(
        year: '*',
        month: '*',
        day: '*',
        week: '*',
        weekOfMonth: '*',
        weekday: '*'
    )
示例
  1. 每月第二个星期五重复模型。
$model->repeat()->complex(weekOfMonth: 2, weekday: Carbon::FRIDAY)
  1. 每月15日重复模型。
$model->repeat()->complex(day: 15)

模型作用域

使用whereOccurresOn作用域获取特定日期发生的模型。

Task::whereOccurresOn(Carbon::make('2023-05-01'))->get()

使用whereOccurresBetween作用域获取在两个特定日期之间发生的模型。

Task::whereOccurresBetween(Carbon::make('2023-05-01'), Carbon::make('2023-05-30'))->get()

1. 结束重复

使用endsAt在特定日期结束发生。

$model->repeat()->daily()->endsAt(
    Carbon::make('2023-06-01')
)

使用endsAfter在 n 次后结束发生。

$model->repeat()->daily()->endsAfter($times);

2. 开始重复

使用startsAt方法在特定日期后开始发生。

$model->repeat()->daily()->startsAt(
    Carbon::make()
)

测试

composer test

致谢

许可证

MIT许可证(MIT)。有关更多信息,请参阅许可证文件