程序骨架
区别于PHP
其他编程语言C/C++
、Java
、Go
等均有一个入口函数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::start
或Swoole\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
、创建新的协程。