PHP code example of kode / process

1. Go to this page and download the library: Download kode/process library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

kode / process example snippets



Kode\Process\Kode;

Kode::serve('http://0.0.0.0:8080', ['workers' => 8])
    ->on('message', fn($conn, $req) => $conn->send('Hello World!'))
    ->start();


Kode\Process\Kode;

Kode::serve('websocket://0.0.0.0:8081', ['workers' => 4])
    ->on('message', fn($conn, $data) => $conn->send($data))
    ->start();


Kode\Process\Kode;

Kode::serve('tcp://0.0.0.0:9000', ['workers' => 4])
    ->on('message', fn($conn, $data) => $conn->send('Echo: ' . $data))
    ->start();

// 强制用某个运行时(swoole | workerman | native)
Kode::serve('http://0.0.0.0:8080', ['workers' => 8], 'swoole')
    ->on('message', fn($conn) => $conn->send('Hello'))
    ->start();

// 显式选用自研 Native 运行时(纯 PHP、零扩展依赖、master-worker 多进程)
Kode::serve('http://0.0.0.0:8080', ['workers' => 8], 'native')
    ->on('message', fn($conn) => $conn->send('Hello'))
    ->start();

$conn->send(string $data, bool $raw = false): bool;   // 发送;raw=true 跳过协议编码
$conn->close(?string $data = null): void;              // 关闭(可带最后一段数据)
$conn->id(): int;                                       // 本 worker 内唯一连接 ID
$conn->remoteAddress(): string;                        // 对端 ip:port
$conn->localAddress(): string;                         // 本端 ip:port
$conn->isAlive(): bool;                                // 是否仍可用
$conn->native(): mixed;                                // 原生对象(Swoole=int fd / Workerman=TcpConnection)
$conn->setContext(string $key, mixed $v): void;        // 关联会话上下文
$conn->getContext(string $key, mixed $default = null): mixed;

$rt = Kode::runtime();

if ($rt->supports(\Kode\Process\Runtime\Capability::HotReload)) {
    $rt->reload();           // 平滑重载(Workerman / Swoole 支持)
}

use Kode\Process\Runtime;

$rt = Runtime::auto();                       // 自动择优(native → swoole → workerman,native 优先)
$rt = Runtime::make('workerman');            // 显式指定
$rt = Runtime::make('native');               // 自研运行时(纯 PHP 零扩展)
$rt = Runtime::make(\Kode\Process\Runtime\RuntimeType::Swoole);

Runtime::available();                        // 当前环境按权重降序的可用运行时
Runtime::preferred();                        // 最优运行时类型
Runtime::isSupported('workerman');           // 该运行时是否可用

print_r(Kode::diagnose());                   // 部署前一键自检(含 Linux 上 ext-event 安装建议)

use Kode\Process\Kode;

$table = Kode::table();          // 自动择优:apcu → sysvshm(零安装)
$table->set('online', 0);
$table->increment('online', 1);

echo $table->get('online');

use Kode\Process\SharedTable;

$table = SharedTable::make('swoole');    // 直接复用 Swoole\Table
$table = SharedTable::make('workerman'); // 直接复用 Workerman\Table

use Kode\Process\Kode;

// 协程(单线程 I/O 并发,委托 kode/fibers)
Kode::go(function () {
    $result = fetchDataFromApi();
    echo json_encode($result);
});

$results = Kode::batch([1, 2, 3, 4, 5], fn($i) => $i * 2, 3);

// 多线程并行(CPU 密集,需 ZTS + ext-parallel)
if (Kode::supportsParallel()) {
    $future = Kode::parallel(fn($x) => heavyCompute($x), 42);
    $result = Kode::awaitParallel($future);
}

use Kode\Process\Kode;

// 服务注册与发现
$node = Kode::join(['address' => 'http://10.0.0.1:8080', 'weight' => 100]);
$nodes = Kode::cluster()->nodes();          // 当前在线节点
$peers = Kode::cluster()->peers();          // 排除自身的其他节点

// 分布式锁
$lock = Kode::lock('order:' . $id, ttl: 30.0);
if ($lock->acquire()) {
    try { /* 临界区 */ } finally { $lock->release(); }
}

// Leader 选举(集群内只有一个节点 isLeader() 为 true)
$elect = Kode::election('scheduler');
$elect->tick();                             // 周期性调用,自动竞选 / 续租 / 让位
if ($elect->isLeader()) { runScheduler(); }

// 负载均衡(round-robin / weighted / least-conn / consistent-hash / random)
$balancer = Kode::balancer('least-conn', $nodes, service: 'api');
$target = $balancer->next();

// 分布式 ID(Snowflake,含 WorkerId 自动分配)
$id = Kode::snowflake()->id();

// 限流(令牌桶,跨进程/跨主机共享计数)
Kode::limiter()->consume('api:ip:' . $ip, 1, limit: 100, window: 60);

use Kode\Process\Cluster;
use Kode\Process\Cluster\Store\RedisStore;

Cluster::useStore(new RedisStore(['host' => '127.0.0.1', 'port' => 6379]));

use Kode\Process\Kode;

Kode::every(2.5, fn() => echo "每 2.5 秒执行\n");      // 周期定时器
Kode::after(10,  fn() => echo "10 秒后执行一次\n");     // 一次性定时器
Kode::cron('* * * * *', fn() => echo "每分钟执行\n");  // Cron 定时器

$id = Kode::after(5, fn() => null);
Kode::clearTimer($id);   // 取消定时器
Kode::tickTimers();      // 在自定义主循环中周期推进

use Kode\Process\Kode;

// 同机多进程:每个调度时刻全集群只执行一次(file 后端自动协调)
Kode::cronCluster('0 0 * * *', fn() => nightlyReport());

// 跨机集群:先配置 Redis 协调后端
Kode::cluster()->make('redis', ['host' => '127.0.0.1', 'port' => 6379]);
Kode::cronCluster('*/5 * * * *', fn() => syncOrders(), lockTtl: 60.0);

use Kode\Process\Kode;

Kode::cron('0 2 * * *', fn() => heavyRebuild());   // 照常注册
// 主循环里改用:
Kode::tickCronOnLeader('scheduler', electionTtl: 15.0);   // 仅 Leader 推进

use Kode\Process\Kode;

// cron 只生产
Kode::cronCluster('*/1 * * * *', function () {
    foreach (fetchDueJobs() as $job) {
        Kode::queue()->dispatch('send_email', $job);   // 入队,交给队列保证至少一次 + 重试
    }
});

// 消费侧(可多 worker 并发消费,天然去重由队列 ack 保证)
Kode::queue()->register('send_email', function (array $data) {
    mail($data['to'], $data['subject'], $data['body']);
    return ['status' => 'sent'];
});


Kode\Process\Kode;

Kode::daemon()
    ->task(fn () => file_put_contents('/tmp/tick', date('c') . "\n", FILE_APPEND))
    ->every(5)                 // 每 5 秒;或 ->cron('0 * * * *')
    ->workers(4)              // 4 个 worker 子进程并行跑
    ->daemonize()             // 脱离终端常驻(可选)
    ->pidFile('/var/run/app.pid')
    ->run();

use Kode\Process\Kode;

Kode::queue()
    ->register('send_email', function (array $data) {
        mail($data['to'], $data['subject'], $data['body']);
        return ['status' => 'sent'];
    });

Kode::queue()->dispatch('send_email', [
    'to'      => '[email protected]',
    'subject' => 'Hello',
    'body'    => 'World',
]);

use Kode\Process\Kode;

// 应用层信号(运行时已自行管理 SIGTERM / SIGINT 等进程信号)
Kode::signal()->register(SIGUSR1, function () {
    echo "收到 SIGUSR1,重载配置\n";
});

// 运行状态监控(写入 status / pid 文件,便于运维排查)
$monitor = Kode::monitor();
$monitor->init(getmypid());

// 进程内发布/订阅事件
Kode::emitter()->on('task.done', fn($id) => echo "任务 $id 完成\n");
Kode::emitter()->emit('task.done', 123);

use Kode\Process\Kode;

Kode::serve('ssl://0.0.0.0:443', [
    'workers' => 4,
    'ssl'     => [
        'local_cert' => '/path/to/cert.pem',
        'local_pk'   => '/path/to/key.pem',
    ],
])
->on('message', fn($conn, $data) => $conn->send('Secure response'))
->start();
bash
kode process start daemon.php --workers=4 --every=5     # 启动(前台)
kode process start daemon.php --daemon --cron='0 0 * * *' # 脱离终端常驻
kode process status                                     # 查看状态
kode process stop                                       # 优雅停止(TERM → 回收 worker → 清理 PID)
kode process restart daemon.php                         # 平滑重启(detached)