frenzzy-ekb / codeigniter-swoole
Codeigniter 3.0+ 的 swoole 适配器
2.1.2
2020-03-11 11:13 UTC
Requires
- php: >=7.0
- ext-swoole: ^4.0.0
Requires (Dev)
- phpunit/phpunit: ^7.2
README
你想要长期任务?计时器?从 FPM 到 CLI?在 FPM 和 CLI 模式下重用代码?
"这很简单!"
这个适配器可以让您在 Codeigniter 框架中轻松使用 swoole。
有了这个适配器,您可以从代码的任何地方启动一个任务(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 文件可以设置一些定时器方法供 swoole 服务器使用,这些定时器将在服务器初始化时启动。
您可以复制 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 许可。