PHP code example of xp-framework / command

1. Go to this page and download the library: Download xp-framework/command 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/ */

    

xp-framework / command example snippets


use util\cmd\{Command, Arg};
use rdbms\DriverManager;
use io\streams\Streams;

/**
 * Performs an SQL query
 */
class Query extends Command {
  private $connection, $query;
  private $verbose= false;

  /** Connection DSN, e.g. `mysql://user:pass@host[:port][/database]` */
  #[Arg(position: 0)]
  public function useConnection(string $dsn) {
    $this->connection= DriverManager::getConnection($dsn);
    $this->connection->connect();
  }

  /** SQL query. Use `-` to read from standard input */
  #[Arg(position: 1)]
  public function useQuery(string $query) {
    if ('-' === $query) {
      $this->query= Streams::readAll($this->in->stream());
    } else {
      $this->query= $query;
    }
  }

  /** Verbose output */
  #[Arg]
  public function useVerbose() {
    $this->verbose= true;
  }

  /** @return int */
  public function run() {
    $this->verbose && $this->out->writeLine('@ ', $this->connection);
    $this->verbose && $this->out->writeLine('>>> ', $this->query);

    $result= $this->connection->open($this->query);
    if ($result->isSuccess()) {
      $this->verbose && $this->out->writeLine('<<< ', $result->affected());
      return $result->affected() ? 0 : 1;
    } else {
      $this->verbose && $this->out->writeLine('<<< Results');
      foreach ($result as $found => $record) {
        $this->out->writeLine($record);
      }
      return isset($found) ? 0 : 2;
    }
  }
}