PHP code example of nashgao / interactive-shell

1. Go to this page and download the library: Download nashgao/interactive-shell library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

nashgao / interactive-shell example snippets




use NashGao\InteractiveShell\Shell;
use NashGao\InteractiveShell\Transport\SwooleSocketTransport;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\ConsoleOutput;

// Create Swoole socket transport pointing to your backend
$transport = new SwooleSocketTransport(
    socketPath: '/var/run/myapp.sock',
    timeout: 30.0
);

// Create shell with custom prompt and aliases
$shell = new Shell(
    transport: $transport,
    prompt: 'myapp> ',
    defaultAliases: [
        'ls' => 'list',
        'q' => 'quit',
    ]
);

// Run the interactive shell
$input = new ArgvInput();
$output = new ConsoleOutput();

$exitCode = $shell->run($input, $output);
exit($exitCode);



use NashGao\InteractiveShell\StreamingShell;
use NashGao\InteractiveShell\Transport\SwooleSocketTransport;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\ConsoleOutput;

// Create streaming transport (Swoole socket example)
$transport = new SwooleSocketTransport(
    socketPath: '/var/run/mqtt-debug.sock',
    timeout: 30.0
);

// Create streaming shell
$shell = new StreamingShell(
    transport: $transport,
    prompt: 'stream> ',
    defaultAliases: []
);

// Run the streaming shell
$input = new ArgvInput();
$output = new ConsoleOutput();

$exitCode = $shell->run($input, $output);
exit($exitCode);

// Command: users list --format=table
// Or simply: users list

// Command: users list --format=json

// Command: users list --format=csv

// Command: users show 1\G
// Or: users show 1 --format=vertical

use NashGao\InteractiveShell\Shell;
use NashGao\InteractiveShell\Formatter\OutputFormat;

$shell = new Shell(
    transport: $transport,
    prompt: 'myapp> ',              // Custom prompt string
    defaultAliases: [                // Pre-configured aliases
        'ls' => 'list',
        'q' => 'quit',
        'h' => 'help',
    ]
);

// Set default output format
$shell->setOutputFormat(OutputFormat::Json);

// Change prompt dynamically
$shell->setPrompt('admin@myapp> ');

use NashGao\InteractiveShell\Transport\SwooleSocketTransport;

$transport = new SwooleSocketTransport(
    socketPath: '/var/run/myapp.sock',
    timeout: 30.0,                    // Socket timeout
);



namespace App\Shell\Transport;

use NashGao\InteractiveShell\Command\CommandResult;
use NashGao\InteractiveShell\Parser\ParsedCommand;
use NashGao\InteractiveShell\Transport\TransportInterface;

final class RedisTransport implements TransportInterface
{
    private \Redis $redis;
    private bool $connected = false;

    public function __construct(
        private readonly string $host = '127.0.0.1',
        private readonly int $port = 6379,
        private readonly float $timeout = 5.0,
    ) {
        $this->redis = new \Redis();
    }

    public function connect(): void
    {
        $this->connected = $this->redis->connect(
            $this->host,
            $this->port,
            $this->timeout
        );

        if (!$this->connected) {
            throw new \RuntimeException("Cannot connect to Redis at {$this->host}:{$this->port}");
        }
    }

    public function disconnect(): void
    {
        if ($this->connected) {
            $this->redis->close();
            $this->connected = false;
        }
    }

    public function isConnected(): bool
    {
        return $this->connected && $this->redis->ping() !== false;
    }

    public function send(ParsedCommand $command): CommandResult
    {
        try {
            // Execute Redis command
            $result = $this->redis->rawCommand(
                $command->command,
                ...$command->arguments
            );

            return CommandResult::success(
                data: $result,
                message: 'OK'
            );
        } catch (\RedisException $e) {
            return CommandResult::failure(
                error: $e->getMessage()
            );
        }
    }

    public function ping(): bool
    {
        try {
            return $this->redis->ping() !== false;
        } catch (\RedisException) {
            return false;
        }
    }

    public function getInfo(): array
    {
        try {
            $info = $this->redis->info();
            return is_array($info) ? $info : [];
        } catch (\RedisException) {
            return [];
        }
    }

    public function getEndpoint(): string
    {
        return "{$this->host}:{$this->port}";
    }
}

$transport = new RedisTransport(host: 'localhost', port: 6379);
$shell = new Shell($transport, prompt: 'redis> ');
$shell->run($input, $output);



namespace App\Shell\Handler;

use NashGao\InteractiveShell\Command\CommandResult;
use NashGao\InteractiveShell\Parser\ParsedCommand;
use NashGao\InteractiveShell\Server\ContextInterface;
use NashGao\InteractiveShell\Server\Handler\CommandHandlerInterface;

final class DatabaseHandler implements CommandHandlerInterface
{
    public function getCommand(): string
    {
        return 'db:status';
    }

    public function handle(ParsedCommand $command, ContextInterface $context): CommandResult
    {
        // Access services via context
        $db = $context->get('database');

        return CommandResult::success(
            data: [
                'connected' => $db->isConnected(),
                'driver' => $db->getDriver(),
                'queries' => $db->getQueryCount(),
            ],
            message: 'Database status retrieved'
        );
    }

    public function getDescription(): string
    {
        return 'Show database connection status';
    }

    public function getUsage(): array
    {
        return ['db:status', 'db:status --verbose'];
    }
}

use NashGao\InteractiveShell\Server\Handler\CommandRegistry;

$registry = new CommandRegistry();

// Register individual handlers
$registry->register(new DatabaseHandler());
$registry->register(new QueueHandler());
$registry->register(new CacheHandler());

// Set a fallback handler for unknown commands
$registry->setFallbackHandler(new UnknownCommandHandler());



return [
    // Enable/disable shell server
    'enabled' => (bool) env('SHELL_ENABLED', true),

    // Unix socket path
    'socket_path' => env('SHELL_SOCKET_PATH', '/var/run/hyperf-shell.sock'),

    // Socket file permissions
    'socket_permissions' => 0660,

    // Register custom handlers
    'handlers' => [
        App\Shell\Handler\DatabaseHandler::class,
        App\Shell\Handler\QueueHandler::class,
    ],
];

use NashGao\InteractiveShell\Shell;
use NashGao\InteractiveShell\Transport\SwooleSocketTransport;

$transport = new SwooleSocketTransport(
    socketPath: '/var/run/hyperf-shell.sock',
    timeout: 30.0
);

$shell = new Shell($transport, prompt: 'hyperf> ');
$shell->run($input, $output);

// Shell execution
$shell->run(InputInterface $input, OutputInterface $output): int
$shell->executeCommand(string $command, OutputInterface $output): int

// Shell control
$shell->isRunning(): bool
$shell->stop(): void

// Configuration
$shell->setPrompt(string $prompt): void
$shell->setOutputFormat(OutputFormat $format): void

// Access components
$shell->getTransport(): TransportInterface
$shell->getAliases(): AliasManager
$shell->getHistory(): HistoryManager

// StreamingShell-specific
$shell->setFilter(FilterExpression $filter): void
$shell->getMessageCount(): int
$shell->getOutputFormatter(): OutputFormatter
bash
# Publish the configuration file
php bin/hyperf.php vendor:publish nashgao/interactive-shell