Luminova Framework

PHP Luminova: Command Execution using Process Handler

Last updated: 2026-11-28 20:57:12

Run commands or PHP callbacks and collect their output.

Luminova’s Process Handler runs a command, a PHP callable, or a stream operation. The chosen executor controls how command output is collected. Call run() to start the operation, wait() when completion is needed, and getResponse() to read the result.


Features

  • Multiple Executors: The class supports running processes using different command execution mechanisms such as:
    • popen
    • proc_open
    • shell_exec
    • exec
  • Closure Support: It can execute callable PHP functions or generators, allowing developers to easily run custom code or produce dynamic outputs.
  • Stream Interface: It handles stream resources for reading or writing data through file descriptors, making it suitable for dealing with files, network streams, etc.
  • Process Lifecycle Management: The class can manage the lifecycle of a process, including starting, running, waiting for completion, and retrieving responses or outputs.
  • Timeouts: It includes the ability to wait for a process with a defined timeout to avoid long-running or hanging processes.

Examples

  1. Execute a command with proc_openFor advanced command execution scenarios, it supports running commands using proc_open, allowing more fine-grained control over input/output streams.

    use Luminova\Utility\Process;
    
    $process = Process::withCommand('echo "Process complete"', Process::EXECUTOR_PROC_OPEN);
    $process->run();
    $process->wait(15); // Wait for up to 15 seconds
    
    if ($process->isComplete()) {
       // Get and output the response
       $response = $process->getResponse();
       echo "Command output:\n";
       var_export($response);
    }
  2. Start a process with a callableSupply a PHP callable when the operation is defined in code. The generator example below shows how to collect yielded output.

    use Luminova\Utility\Process;
    
    $process = Process::withCallback(static function (): Generator {
        yield "Hello, World!";
    });
    $process->run();
    $process->wait(2);
  3. Shell Command Execution with shell_exec:This feature enables executing system commands using shell_exec and capturing their output.

    use Luminova\Utility\Process;
    
    $process = Process::withCommand('ls -la', Process::EXECUTOR_SHELL);
    $process->run();
  4. Handling Stream Resources:The class can read from or write to streams, like files or network resources, using the stream interface.

    use Luminova\Utility\Process;
    
    $stream = fopen('path/to/file.txt', 'r');
    $process = Process::withStream($stream);
    $process->run();
    $process->wait(2);
    
    // Get the contents read from the stream
    if ($process->isComplete()) {
       $response = $process->getResponse();
       echo "Stream content:\n$response";
    }
  5. Running a Command with popen:The Process class allows for running shell commands using popen, providing control over the command output and process flow.

    use Luminova\Utility\Process;
    
    $process = Process::withCommand('ls -la', Process::EXECUTOR_POPEN);
  6. Waiting for Generator Completion:It can run and wait for PHP generators to complete, making it a versatile tool for handling asynchronous-like operations.

    use Luminova\Utility\Process;
    
    $generator = function() {
       yield "Part 1";
       yield "Part 2";
    };
    $process = Process::withCallback($generator);
    $process->run();
    $process->wait(2);
    
    // Get the generator's output
    if ($process->isComplete()) {
       $response = $process->getResponse();
       echo "Generator output:\n" . implode("\n", array_filter((array) $response, 'is_string'));
    }

Class Definition

  • Full namespace: Luminova\Utility\Process
  • This class is an ordinary class.

Constants

These constants are predefined process executors which can be pass directory during initialization or along with withCommand method.

ConstantVisibilityTypeDescription
EXECUTOR_POPENpublicstringExecutes a command using popen, opening a pipe for process I/O.
EXECUTOR_EXECpublicstringExecutes a command using exec, running it directly via the shell.
EXECUTOR_SHELLpublicstringExecutes a command using shell_exec, capturing output from the shell.
EXECUTOR_PROC_OPENpublicstringExecutes a command using proc_open, offering more control over process execution and I/O streams.
EXECUTOR_CALLBACKpublicstringExecutes process using a custom callback function, allowing flexible execution logic.
EXECUTOR_STREAMpublicstringExecutes a process using streams, enabling direct access to input/output streams during execution.

Process instances cannot be serialized. Store any configuration needed to recreate a process separately.


Methods

__construct

Process constructor.

public function __construct(
    mixed $input,
    string $executor = self::EXECUTOR_PROC_OPEN,
    ?string $cwd = null,
    ?array $env = null
)

Parameters:

ParameterTypeDescription
$inputmixedCommand string, callable, or stream to be executed.
$executorstringThe process executor type (e.g, Process::EXECUTOR_*) (default: self::EXECUTOR_PROC_OPEN).
$cwdstring\|nullOptional working directory (default: null).
$envarray<int\|string,mixed>\|nullOptional environment variables (default: null).

run

Runs the process based on the provided input and executor.

public function run(): void

Return:

void - This method does not return a value.

Throws:


withCallback

Creates a Process instance with a callback.

public static function withCallback(callable $callable): self

Parameters:

ParameterTypeDescription
$callablecallableThe callable to be executed.

Return:

self - Return new static process instance.


withStream

Creates a Process instance with a stream.

public static function withStream(mixed $stream): self

Parameters:

ParameterTypeDescription
$streammixedThe stream resource to read from.

Return:

self - Return new static process instance.


withCommand

Creates a Process instance with a command.

public static function withCommand(
    array|string $command,
    string $executor = self::EXECUTOR_POPEN,
    ?string $cwd = null,
    ?array $envs = null
): self

Parameters:

ParameterTypeDescription
$commandarray<int\|string,mixed>\|stringThe command to be executed.
$executorstringThe executor method to use (default: Process::EXECUTOR_POPEN).
$cwdstring\|nullOptional working directory (default: null).
$envsarray<string,mixed>\|nullOptional environment variables (default: null).

Return:

self - Return new static process instance.


isComplete

Checks if the process has completed execution.

public function isComplete(): bool

Return:

bool - Return true if the process has finished; otherwise, false.


isRunning

Check whether the handler has an open execution.

public function isRunning(): bool

Return:

bool - True while the handler is open. Call wait() to collect the response and complete the handler lifecycle.


isPtySupported

Determines if PTY (Pseudo-Terminal) is supported on the current system.

public static function isPtySupported(): bool

Return:

bool - Return true if PTY is supported, false otherwise.


isTtySupported

Checks if the current system supports TTY (Teletypewriter).

public static function isTtySupported(): bool

Return:

bool - Return true if TTY is supported, false otherwise.


getResponse

Retrieves the output response from the executed process.The response output, which can be of any type (e.g., string, array).

public function getResponse(): mixed

Return:

mixed - Returns null if the process has not yet run or if no response is available.


getPid

Returns the Pid (process identifier), if applicable.

public function getPid(): ?int

Return:

int|null - The process ID when the handler is open and has a process resource, otherwise null.


getInfo

Read the available process status information.

public function getInfo(): array|bool

Return:

array<string,mixed>|bool - Stored process metadata when the handler is open and has a process resource, or false otherwise. The metadata may be empty. The process status can contain the following fields.

KeyTypeDescription
commandstringCommand line used to start the process.
pidintProcess identifier.
runningboolWhether the process was running when status was read.
signaledboolWhether a signal terminated the process.
stoppedboolWhether a signal stopped the process.
exitcodeintReported exit code.
termsigintTerminating signal number.
stopsigintStopping signal number.
cachedboolWhether PHP reported a cached exit code, when available.

getStartTime

Retrieve the process start time in seconds.

public function getStartTime(): float

Return:

float - Timestamp in seconds set when wait() begins.

Throws:


getWorkingDirectory

Gets the working directory.

public function getWorkingDirectory(): ?string

Return:

string|null - Return the current working directory.


getCommand

Sanitize, replace and retrieve command.

public function getCommand(): string

Return:

string - Return command string to be executed.

Throws:


setWorkingDirectory

Sets the current working directory.

public function setWorkingDirectory(string $cwd): self

Parameters:

ParameterTypeDescription
$cwdstringThe current working directory.

Return:

self - Return the instance of process class.

Throws:


setEnvironment

Sets the environment variables.

public function setEnvironment(array $envs): self

Parameters:

ParameterTypeDescription
$envsarray<string,mixed>The environment variables.

Return:

self - Return the instance of process class.

Throws:


setMode

Sets the mode for opens process file pointer.

public function setMode(string $mode): self

Parameters:

ParameterTypeDescription
$modestringThe mode to use.

Return:

self - Return the instance of process class.

Throws:


setDescriptors

Sets the descriptors specifications.

public function setDescriptors(array $descriptors): self

Parameters:

ParameterTypeDescription
$descriptorsarray<int\|string,mixed>The descriptors specifications.

Return:

self - Return the instance of process class.

Throws:


setOptions

Set the process options before execution.

This method allows setting specific options for the process, such as blocking pipes orcreating a new process group. Options cannot be modified once the process is running.

public function setOptions(array $options): self

Parameters:

ParameterTypeDescription
$optionsarray<string,mixed>An associative array of options to set.

Return:

self - Return the instance of process class.

Throws:

Supported options include:

  • blocking_pipes: Controls whether the pipes should block during I/O.
  • create_process_group: Determines if the process should be run in a new group.
  • create_new_console: Launches the process in a new console window (Windows only).
  • bypass_shell: Bypass the shell when launching the process (Linux/Windows).
  • detach_process: Detaches the process, allowing it to run independently (Linux/Windows).
  • use_pty: Use a pseudo-terminal (PTY) for the process (Unix systems only).
  • inherit_environment: Inherit the environment variables from the parent process.
  • redirect_stderr: Redirect stderr to stdout (combine output streams).
  • suppress_errors: Suppress PHP errors or warnings during the process execution.

getDescriptors

Gets the descriptors for the process.

public function getDescriptors(): array

Return:

array<array-key,mixed> - Custom descriptors when configured, or the default specifications keyed by file descriptor.

KeyTypeDescription
0array<int,string>Standard input opened as a readable pipe by the child.
1array<int,string>Standard output opened as a writable pipe by the child.
2array<int,string>Standard error opened as a writable pipe by the child.

wait

Waits for the process to complete and collects output.

public function wait(int $timeout = 0): void

Parameters:

ParameterTypeDescription
$timeoutintMaximum time to wait in seconds (default: 0 for no timeout).

Return:

void - This method does not return a value.

Throws: