depaco / codeigniter-swoole
Codeigniter 3.0+ 的 swoole 适配器
v1.0.8
2021-05-28 00:26 UTC
Requires
- php: >=7.0
- ext-swoole: ^4.0.0
Requires (Dev)
- phpunit/phpunit: ^7.2
README
您需要长时间运行的任务?定时器?从 FPM 到 CLI?在 FPM 和 CLI 模式下重用代码?
"这很简单!"
这个适配器会让您在 Codeigniter 框架中使用 swoole 变得非常简单。
使用此适配器,您可以从代码的任何地方(FPM)启动任务(CLI)。
这意味着您可以从 FPM 进程启动 CLI 任务。
安装
composer require lanlin/codeigniter-swoole
如何操作
- 首先,当然您必须将
codeigniter-swoole
安装到您的 Codeigniter 项目中。 - (此步骤为可选)将这两个配置文件
swoole.php
和timers.php
从src/Helper
复制到您的application/config
文件夹。 - 启动 swoole 服务器
php index.php swoole/server/start
- 现在您可以使用
\CiSwoole\Core\Client::send($data)
启动任务! - 没有第 5 步。
什么是任务?
任务只是您的 codeigniter 控制器中的一个方法,因此几乎任何控制器方法都可以用作任务。
让我们看看代码
\CiSwoole\Core\Client::send( [ 'route' => 'your/route/uri/to/a/method' 'params' => ['test' => 666] ], $fd, $callback);
使用 route
来查找要作为任务调用的哪个方法,以及 params
是您可能想要传递给任务的参数数组。
使用 fd
和 callback
参数来通知任务错误。
所以,这就全部了!
服务器 CLI 命令
// start the swoole server php index.php swoole/server/start // stop the swoole server php index.php swoole/server/stop // reload all wokers of swoole server php index.php swoole/server/reload
更多内容
第 2 步中复制的文件是该适配器的配置文件。
swoole.php
文件可以设置主机、端口、日志文件等。
timers.php
文件可以设置一些定时器方法,这些定时器将在服务器初始化后启动。
您可以将 tests/application
复制到您的 application
中进行测试。示例与以下相同。
class Test extends CI_Controller { // ------------------------------------------------------------------------------ /** * here's the task 'tests/test/task' */ public function task() { $data = $this->input->post(); // as you see, params worked like normally post data log_message('info', var_export($data, true)); } // ------------------------------------------------------------------------------ /** * here's the timer method * * you should copay timers.php to your config folder, * then add $timers['tests/test/task_timer'] = 10000; and start the swoole server. * * this method would be called every 10 seconds per time. */ public function task_timer() { log_message('info', 'timer works!'); } // ------------------------------------------------------------------------------ /** * send data to task */ public function send() { try { \CiSwoole\Core\Client::send( [ 'route' => 'tests/test/task', 'params' => ['hope' => 'it works!'], ]); } catch (\Exception $e) { log_message('error', $e->getMessage()); log_message('error', $e->getTraceAsString()); } } // ------------------------------------------------------------------------------ }
许可证
该项目采用 MIT 许可证。