rutay / laravel-ccmd
ccmd 是一个 Laravel 包,它提供了一种更简洁的方式来定义和调度命令。
dev-master
2021-04-12 20:55 UTC
This package is not auto-updated.
Last update: 2024-09-22 02:07:45 UTC
README
CCMD (带注释的命令) 包是一个 Laravel 扩展,允许您更容易地编写和调度命令。
安装
composer require rutay/laravel-ccmd
用法
定义
CCMD (通过此包定义的命令) 可以这样定义
// App\SomeClass.php /** * @command * * @signature your_app:greet {person} * @description A simple command that greets a person. * * @repeat '*\5 * * * *' */ function helloWorld(Command $command) // The argument $person could even be injected through function parameters. { $person = $command->argument('person'); // ... }
遵循以下规则
@command
和@signature
必须定义(其他字段为可选)。@repeat
可以是任何有效的 PHP 字符串(它使用eval()
进行解析)。如果使用 cron 表达式,请记住提供 ''。- 在 cron 表达式中,您不能使用
*/
,因为它会关闭注释。您可以使用*\
代替。 - 命令函数可以具有任何名称。
- 命令函数的参数使用以下顺序解析
- 类型提示为
Illuminate\Console\Command
,然后将其与当前的(自动生成的)Laravel 命令一起提供。 - 类型提示可以通过 Laravel 的 ServiceContainer 进行解析。
- 参数的名称与命令的参数或选项相匹配。
- 无效的函数原型定义。
- 类型提示为
订阅
就像使用任何其他 Laravel 命令一样,您需要在 App\Console\Kernel.php
中注册 CCMD。
我建议以下方法
protected $ccmds = [ // Fill this array with classes that have CCMDs. SomeClass::class, // ... ]; protected function commands() { (new CCMDLoader())->load($this->ccmds); // There it creates the Laravel's commands. // ... } protected function schedule(Schedule $schedule) { (new CCMDLoader())->schedule($this->ccmds, $schedule); // There it creates the schedules that call the Laravel's commands. // ... }
原因
编写此包的需要是在我需要开发一个必须处理多个任务的平台时出现的。对于这些任务中的每一个,我都想为它创建一个命令(这对于测试也很有用),并且它还必须通过 cron 进行调度。
所以我发现自己写了很多重复的代码
// App\Platform.php function executeTask1() { /* ... */ } function executeTask2() { /* ... */ } function executeTask3() { /* ... */ } // App\Console\Kernel.php Artisan::command("platform:task1", function (Platform $platform) { $platform->executeTask1(); })->purpose("desc1"); Artisan::command("platform:task2", function (Platform $platform) { $platform->executeTask2(); })->purpose("desc2"); Artisan::command("platform:task3", function (Platform $platform) { $platform->executeTask3(); })->purpose("desc3"); $schedule->command("platform:task1")->cron('*/5 * * * *'); $schedule->command("platform:task2")->cron('*/6 * * * *'); $schedule->command("platform:task3")->cron('*/7 * * * *');
多亏了这个系统,现在我可以这样解决这个问题
/** * @command * * @signature platform:task1 * @description desc1 * * @repeat '*\5 * * * *' */ function executeTask1() { /* ... */ } /** * @command * * @signature platform:task2 * @description desc2 * * @repeat '*\6 * * * *' */ function executeTask2() { /* ... */ } /** * @command * * @signature platform:task3 * @description desc3 * * @repeat '*\7 * * * *' */ function executeTask3() { /* ... */ }