mohammedmanssour / laravel-recurring-models
为Laravel模型添加可重复功能
Requires
- php: ^8.1
- illuminate/contracts: ^11.1
- spatie/laravel-package-tools: ^1.14.0
Requires (Dev)
- larastan/larastan: ^2.9
- laravel/pint: ^1.0
- nunomaduro/collision: ^8.1
- orchestra/testbench: ^9.0
- phpstan/extension-installer: ^1.1
- phpstan/phpstan-deprecation-rules: ^1.0
- phpstan/phpstan-phpunit: ^1.0
This package is auto-updated.
Last update: 2024-09-10 20:48:23 UTC
README
介绍我们的Laravel Recurring包 - 为Laravel模型添加可重复功能的终极解决方案!无论您需要简单的每天、每周或每n天重复,还是更复杂的模式,如每月第二个星期五重复模型,我们的包都能满足您的需求。通过无缝集成到您的Laravel应用程序中,您可以使用几行代码轻松管理和自动化重复任务。
安装
您可以通过composer安装此包
composer require mohammedmanssour/laravel-recurring-models
您可以使用以下命令发布和运行迁移
php artisan vendor:publish --tag="recurring-models-migrations"
php artisan migrate
用法
为模型添加可重复功能
- 确保您的模型实现了
Repeatable
契约。
use MohammedManssour\LaravelRecurringModels\Contracts\Repeatable as RepeatableContract; class Task extends Model implements RepeatableContract { }
- 将
Repeatable
特质添加到您的模型中
use MohammedManssour\LaravelRecurringModels\Contracts\Repeatable as RepeatableContract; use MohammedManssour\LaravelRecurringModels\Concerns\Repeatable; class Task extends Model implements RepeatableContract { use Repeatable; }
- 可选,自定义模型基准日期。
/** * 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
辅助类:daily
、everyNDays
、weekly
和complex
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: '*' )
示例
- 每月第二个星期五重复模型。
$model->repeat()->complex(weekOfMonth: 2, weekday: Carbon::FRIDAY)
- 每月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)。有关更多信息,请参阅许可证文件。