× 警告!旧版文档已经暂停维护,请查看新版文档。点击前往新版文档

程序骨架

区别于PHP其他编程语言C/C++JavaGo等均有一个入口函数main,所有代码必须要在main函数中开始执行。

PHP语言是允许在任意.php直接写程序代码,并可以直接php your_file.php执行的。这更加灵活,但在Swoole程序中产生了很多混乱。为底层设计带来很多难题。

以下使用index.php表示程序入口

4.4版本开始,我们正在收敛程序入口,更加标准化、规范化。在5.0版本中我们将彻底移除对PHP直写代码方式的支持。

程序入口

4.4或更高版本中,建议Swoole工程师使用以下方式作为程序单一入口。

  • Swoole\Server::start:多进程的Server程序
  • Swoole\Process\Pool::start:多进程程序
  • Swoole\Coroutine\Scheduler::startSwoole\Coroutine\run:单进程协程程序 (相当于main函数)
  • Swoole\Process::start:自定义的子进程程序

Swoole提供的各种组件,如go创建协程、Co::sleep睡眠函数等,应该只在对应程序约定的回调函数、主函数中使用。

因此在index.php中只允许有Swoole\Server::start等上述四种方式启动。底层允许在index.php使用多次启动器。

实例

$s = new Co\Scheduler();
$s->add(function () {
    file_get_contents("http://server:9501/start");
});
$s->start();

$serv = new Swoole\Server;
$serv->on('Receive', function () {});
$serv->start();

$s = new Co\Scheduler();
$s->add(function () {
    file_get_contents("http://server:9501/stop");
});
$s->start();

废弃警告

在未来5.0的版本中,我们将禁止以下行为:

  • index.php中直接使用go创建协程
  • index.php中使用Swoole\Event::wait

错误实例 1

go(function () {
    Co::sleep(1);
});
Swoole\Event::wait();

这里未使用任何启动器,直接使用go、并且使用了Swoole\Event::wait()等待事件。

错误实例 2

go(function () {
    Co::sleep(1);
});

错误实例2中在index.php程序末尾没有添加Swoole\Event::wait(),底层会调用register_shutdown_function在程序结束回调函数中执行Swoole\Event::wait(),这里也是错误的。

正确实例 1

use Swoole\Coroutine;

$s = new Coroutine\Scheduler();
$s->add(function () {
    Co::sleep(1);
    Coroutine::create(function () {
        echo "Co 2\n";
    });
});
$s->start();

// 或是快捷方式, 和上面等价

Coroutine\run(function() {
    Co::sleep(1);
    Coroutine::create(function () {
        echo "Co 2\n";
    });
});

使用了Coroutine\Scheduler::start启动器,在Scheduler对象上注册协程,并在启动的协程中使用Co::sleep协程API、创建新的协程。

正确实例 2

$serv = new Swoole\Server;
$serv->on('WorkerStart', function () {
    Co::sleep(1);
    go(function () {
        echo "Co 2\n";
    });
});
$serv->on('Receive', function () {});
$serv->start();

使用了Server::start启动器,并在onWorkerStart回调函数中使用使用Co::sleep协程API、创建新的协程。