ThinkSSL🔒 一键申购 5分钟快速签发 30天无理由退款 购买更放心 广告
## 后台运行 借助 Swoole 让 Mix 可以在代码中实现原本 `nohup &` 的功能,让守护进程能持续在后台执行。 ## 用法 ``` use \Mix\Helper\ProcessHelper; ProcessHelper::daemon(bool $noclose = false, bool $nochdir = true) ``` ## 说明 由于 Swoole 4 所有协程必须在 Swoole\Coroutine\Scheduler 启动,加上无法再协程中 Fork [#3005](https://github.com/swoole/swoole-src/issues/3005),因此用户无法在 Command::class 等业务代码中直接使用 `ProcessHelper::daemon` 实现后台执行,根据以上限制条件 Fork 只能在 Scheduler 启动之前执行,因此 Mix 通过在 `mix/console` >= v2.1.1 加入事件调度器调度 CommandBeforeExecuteEvent 事件,用户可在 Scheduler 启动之前执行 `ProcessHelper::daemon` 实现后台执行。 ## CommandBeforeExecuteEvent 事件处理 首先我们创建一个 CommandListener::class 监听器,用来监听 CommandBeforeExecuteEvent 事件 [>> 查看 CommandListener::class 源码 <<](https://github.com/mix-php/mix-skeleton/tree/v2.1/app/Common/Listeners/CommandListener.php) - CommandBeforeExecuteEvent 事件包含一个 command 的 string 类型属性,值为当前执行的命令的类路径 - 通过 switch case 可以选择让指定的 Command::class 执行 ProcessHelper::daemon() 然后我们需要在 [beans/event](https://github.com/mix-php/mix-skeleton/tree/v2.1/manifest/beans/event.php) 配置中将 CommandListener::class 监听器注册到 EventDispatcher::class 事件调度器中。