所有的进程必须实现 \Hyperf\Contract\ProcessInterface 接口
Hyperf 提供了 \Hyperf\Process\AbstractProcess 抽象实现类
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact [email protected]
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace Hyperf\Contract;
use Swoole\Coroutine\Http\Server as CoHttpServer;
use Swoole\Coroutine\Server as CoServer;
use Swoole\Server;
interface ProcessInterface
{
/**
* Create the process object according to process number and bind to server.
* @param CoHttpServer|CoServer|Server $server
*/
public function bind($server): void;
/**
* Determine if the process should start ?
* @param CoServer|Server $server
*/
public function isEnable($server): bool;
/**
* The logical of process will place in here.
*/
public function handle(): void;
}
实际把进程添加到Swoole Service的代码在 \Hyperf\Process\Listener\BootProcessListener::process 通过事件-监听模式触发。
/**
* Handle the Event when the event is triggered, all listeners will
* complete before the event is returned to the EventDispatcher.
*/
public function process(object $event)
{
/** @var BeforeMainServerStart $event */
$server = $event->server;
$serverConfig = $event->serverConfig;
$serverProcesses = $serverConfig['processes'] ?? [];
$processes = $this->config->get('processes', []);
$annotationProcesses = $this->getAnnotationProcesses();
// Retrieve the processes have been registered.
$processes = array_merge($serverProcesses, $processes, ProcessManager::all(), array_keys($annotationProcesses));
foreach ($processes as $process) {
if (is_string($process)) {
$instance = $this->container->get($process);
if (isset($annotationProcesses[$process])) {
foreach ($annotationProcesses[$process] as $property => $value) {
if (property_exists($instance, $property) && ! is_null($value)) {
$instance->{$property} = $value;
}
}
}
} else {
$instance = $process;
}
if ($instance instanceof ProcessInterface) {
$instance->isEnable($server) && $instance->bind($server);
}
}
}