innmind/virtual-machine

1.0.0 2021-03-26 16:17 UTC

This package is auto-updated.

Last update: 2024-11-27 00:26:02 UTC


README

Build Status codecov Type Coverage

Small abstraction on top of innmind/cli to manage processes and filesystem within the context of a project.

This is intended for CLI applications where the binary must be run within the context of the project.

Note: do not use this package for CLI tools that you can run from anywhere in your operating system.

Installation

composer require innmind/virtual-machine

Usage

# some/binary.php

use Innmind\CLI\{
    Main,
    Environment,
};
use Innmind\OperatingSystem\OperatingSystem;
use Innmind\VirtualMachine\{
    VirtualMachine,
    Command,
};
use Innmind\Server\Status;
use Innmind\Server\Control;
use Innmind\Immutable\Set;

new class extends Main
{
    protected function main(Environment $env, OperatingSystem $os): void
    {
        $vm = VirtualMachine::of($env, $os);

        if ($env->workingDirectory()->toString() !== __DIR__.'/') {
            throw new \Exception('binary.php must me executed from within the "some/" directory')
        }

        // all required paths are resolved from the working directory so you don't
        // have to do the resolution yourself, and it's safe to require a file
        // from anywhere within your app
        $vm->filesystem()->require(Path::of('other_file.php'));

        // this is similar to $os->status()->processes()->all() but here the set
        // will only contain processes that are running whithin the working
        // directory for the same "binary.php" bin
        /** @var Set<Status\Server\Process> */
        $processes = $vm->processes()->all();

        // this is a shortcut to start a new process with the command
        // "php binary.php 'some-command'" started within the same working
        // directory. So you don't have to repeat the the binary name and
        // specify the working directory. The process is started in the foreground.
        /** @var Control\Server\Process */
        $process = $vm->processes()->execute(Command::of('some-command'));

        // Same as the line above except the process is started in the background
        $vm->processes()->daemon(Command::of('some-daemon'));
    }
}

Note: of course you can name your bin file anyway you want, not just binary.php.