innmind/operating-system

对脚本运行的整体系统的抽象

5.2.0 2024-07-14 13:06 UTC

README

Build Status codecov Type Coverage

对PHP代码运行的操作系统大部分内容的抽象。

目标是更抽象地处理操作系统(而不是处理具体、低层的细节)。

重要

您必须使用vimeo/psalm来确保您正确使用此库。

安装

composer require innmind/operating-system

文档

文档位于documentation/文件夹中。

用法

use Innmind\OperatingSystem\Factory;

$os = Factory::build();

想要访问系统时钟吗?

$os->clock()将返回一个Innmind\TimeContinuum\Clock的实例。

想要访问文件系统吗?

use Innmind\Url\Path;

$adapter = $os->filesystem()->mount(Path::of('/var/data/'));

$adapter是一个Innmind\Filesystem\Adapter的实例。

想要列出系统上运行的所有进程吗?

$os->status()->processes()->all()将返回一个包含Inmmind\Immutable\Set<Innmind\Server\Status\Server\Process>的映射。

想要在系统上运行一个命令吗?

use Innmind\Server\Control\Server\Command;

$process = $os
    ->control()
    ->processes()
    ->execute(Command::foreground('echo foo'));

$process是一个Innmind\Server\Control\Server\Process的实例。

想要打开通向外部世界的端口吗?

use Innmind\Socket\Internet\Transport;
use Innmind\IP\IPv4;
use Innmind\Url\Authority\Port;

$server = $os
    ->ports()
    ->open(
        Transport::tcp(),
        IPv4::localhost(),
        Port::of(1337),
    )
    ->match(
        static fn($server) => $server->unwrap(),
        static fn() => throw new \RuntimeException('Cannot open the socket'),
    );

$server是一个Innmind\Socket\Server的实例。

想要打开本地套接字吗?

# process A
use Innmind\Socket\Address\Unix;

$server = $os->sockets()->open(Unix::of('/tmp/foo.sock'))->match(
    static fn($server) => $server->unwrap(),
    static fn() => throw new \RuntimeException('Cannot open the socket'),
);

$server是一个Innmind\Socket\Server的实例。

# process B
use Innmind\Socket\Address\Unix;

$client = $os->sockets()->connectTo(Unix::of('/tmp/foo.sock'))->match(
    static fn($client) => $client->unwrap(),
    static fn() => throw new \RuntimeException('Cannot connect to the socket'),
);

$client是一个Innmind\Socket\Client的实例。

想要在远程服务器上执行命令吗?

use Innmind\Url\Url;
use Innmind\Server\Control\Server\Command;

$process = $os
    ->remote()
    ->ssh(Url::of('ssh://user@server-address:1337'))
    ->processes()
    ->execute(Command::foreground('ls'));

$process是一个Innmind\Server\Control\Server\Process的实例。

想要进行HTTP调用吗?

use Innmind\Http\{
    Message\Request\Request,
    Message\Method,
    ProtocolVersion,
};
use Innmind\Url\Url;

$response = $os
    ->remote()
    ->http()(new Request(
        Url::of('http://example.com'),
        Method::get,
        ProtocolVersion::v20,
    ));

想要访问当前进程ID吗?

$os->process()->id();

想要暂停当前进程吗?

use Innmind\TimeContinuum\Earth\Period\Minute;

$os->process()->halt(new Minute(1));

想要监听信号吗?

use Innmind\Signals\Signal;

$os->process()->signals()->listen(Signal::terminate, function() {
    // handle the signal here
});