juststeveking / os-process
一个PHP包,用于以面向对象的方式处理操作系统进程。
1.0.0
2022-08-25 09:30 UTC
Requires
- php: ^8.1
- symfony/process: ^6.1
Requires (Dev)
- laravel/pint: ^1.1
- pestphp/pest: ^1.21
- phpstan/phpstan: ^1.8
README
此包是围绕Symfony Process组件的一个包装器,并构建了一个面向对象且用户友好的API。
安装
composer require juststeveking/os-process
用法
要开始使用此包,您首先需要为要使用的进程创建一个抽象。我将在这里向您介绍这个过程。
我们为Terraform创建一个抽象
use JustSteveKing\OS\Contracts\ProcessContract; class Terraform implements ProcessContract { // }
ProcessContract
意味着您必须实现一个build
方法,该方法将返回一个构建好的Symfony Process,然后我们可以运行它。
use JustSteveKing\OS\Contracts\CommandContract; use JustSteveKing\OS\Contracts\ProcessContract; use Symfony\Component\Process\Process; class Terraform implements ProcessContract { private CommandContract $command; public function build() : Process { return new Process( command: $this->command->toArgs(), ); } }
现在让我们创建一个命令
use JustSteveKing\OS\Contracts\CommandContract; class TerraformCommand implements CommandContract { public function __construct( public readonly array $args = [], public readonly null|string $executable = null, ) {} public function toArgs() : array { $executable = (new ExecutableFinder())->find( name: $this->executable ?? 'terraform', ); if (null === $executable) { throw new InvalidArgumentException( message: "Cannot find executable for [$this->executable].", ); } return array_merge( [$executable], $this->args, ); } }
现在我们只需要在抽象中构建和分配这个命令
use JustSteveKing\OS\Contracts\CommandContract; use JustSteveKing\OS\Contracts\ProcessContract; use Symfony\Component\Process\Process; class Terraform implements ProcessContract { private CommandContract $command; public function apply(): Process { $this->command = new TerraformCommand( executable: 'terraform', ); return $this->build(); } public function build() : Process { return new Process( command: $this->command->toArgs(), ); } }
现在我们可以在代码中处理这个进程了
$terraform = new Terraform(); $terraform->apply()->run(); // Will run `terraform apply` in an OS process.
您还可以获取有关进程的信息
$terraform = new Terraform(); $process = $terraform->apply(); // The process variable contains an instance of Symfony\Component\Process $process->run(); // run `terraform apply` in an OS process. // Obtaining information about the process $output = $process->getOutput(); // Output of the command $error = $process->getErrorOutput(); // Error output $commandLine = $process->getCommandLine(); // Obtaining the complete command
获取实时进程输出
$terraform = new Terraform(); $process = $terraform->apply(); // The process variable contains an instance of Symfony\Component\Process $process->start(); // start `terraform apply` in an OS process. (start not run) $process->wait(function ($type, $buffer) { if (\Symfony\Component\Process\Process::ERR === $type) { echo 'ERR > '.$buffer; } else { echo 'OUT > '.$buffer; } });