Skip to content

PHP CliDispatch

Andrew Male edited this page Oct 15, 2015 · 1 revision

Home » Dispatch Types

Contents

Purpose

The CliDispatch dispatch class provides basic structure for any requests sent through the command line interface (CLI) of PHP. The default loading file for the N2f class will store argument and environment information inside a CliDispatch when it either recognizes a request has been made through CLI or is being mocked through CLI (occurs during certain extension routines built into the core).

Code Docs

Automatically generated documentation for CliDispatch is available here:

http://n2framework.com/phpDoc/v2.0.1/classes/N2f.CliDispatch.html

Basic Usage

As with all dispatch types, the dispatch must be both instantiated and then initialized before it will possibly be valid for use. A CliDispatch must be at least provided argument information during initialization. The following shows all three ways of creating and initializing a CliDispatch object:

// Instantiate the dispatch
$Disp = new \N2f\CliDispatch();

// Initialize with just the CLI argument list, $argv
$Disp->Initialize($argv);

// Initialize with $argv as part of an array
$Disp->Initialize(array('argv' => $argv));

// Initialize with a console helper
$Ch = new \N2f\ConsoleHelper($argc, $argv);
$Disp->Initialize(array('ConsoleHelper' => $Ch));

Helper Methods

Each valid instance of CliDispatch will also provide some extra methods to help with CLI interactions:

// Return if the internal ConsoleHelper believes this to be a Windows OS
if ($Disp->IsWindows()) {
  // do something Windows-specific
}

// -----------

// Get the internal ConsoleHelper's parameters
$Params = $Disp->GetParameters();

// If the third parameter is "verbose"
if ($Params[2] == "-verbose") {
  // enable verbose output
}

// -----------

// Get the parameters that were passed to the CliDispatch
$EnvInput = $Disp->GetEnvParameters();

// Loop through raw parameters
foreach (array_values($EnvInput['argv']) as $arg) {
  // Output raw argument
}

// -----------

// Get an associative array of the internal ConsoleHelper's parameters
$Params = $Disp->GetAssocParameters();

// Loop through parameters
foreach ($Params as $Key => $Val) {
  if ($key == 'myparam') {
    // do something with the value
  }
}

// -----------

// Return the internal ConsoleHelper instance
$Ch = $Disp->GetConsoleHelper();

PHP Links

phpDocs

Clone this wiki locally