[:de]PHP-Commandline-Parameter mit Console_Getopt[:en]PHP-Commandline-Parameter with Console_Getopt

[:de]Aus der Historie heraus verwenden die meisten Entwickler PHP hauptsächlich als serverseitige Skriptsprache zur Erstellung von Webseiten oder Webanwendungen. Mit PHP kann man jedoch noch viel mehr machen: es bietet ein Commandline-Interface, welches ermöglicht, auch unter verschiedenen OS Shell-Scripts zu schreiben und zu verwenden.

Um übergebene Parameter auszuwerten, bedient man sich der dafür reservierten Variable $argv.

[:en]Mainly due to historical reasons my guess is most developers are using php as a language to build web pages and web applications. PHP can do alot more: it has a commandline interface, which enables you to write scripts using several different enviroments.

Parameters are stored in a special variable $argv.

[:de]Beispiel 1: test_argv.php
[php]
<?php
var_dump($argv);
?>
[/php]

[:en]Example 1: test_argv.php
[php]
<?php
var_dump($argv);
?>
[/php]

[:de]Ausgabe von Beispiel 1:
[shell]
d:\php5> php.exe test_argv.php IchBinParam1 UndIch2
array(3) {
[0]=>
string(13) "test_argv.php"
[1]=>
string(12) "IchBinParam1"
[2]=>
string(7) "UndIch2"
}
[/shell]

[:en]Output Example 1:
[shell]
d:\php5> php.exe test_argv.php IchBinParam1 UndIch2
array(3) {
[0]=>
string(13) "test_argv.php"
[1]=>
string(12) "IchBinParam1"
[2]=>
string(7) "UndIch2"
}
[/shell]

[:de]So weit, so gut. Wenn es jetzt darum geht, die Argumente zu parsen und zu prüfen, kann so ein Konstrukt rund um $argv schnell recht aufwändig werden. Um dies zu erleichtern, gibt es im PEAR-Paket eine kleine Klasse namens Console_Getopt.

[:en]Not too bad so far. If you now want to start parsing and checking parameters, such a structure can easily get complicated. To make things easier, there is a little class called Console_Getopt in the PEAR project.

[:de]Installation
Falls man PEAR verwendet, kann man die Klasse sehr einfach darüber installieren.
[shell]
d:\php5> pear install Console_Getopt-1.3.0
[/shell]

Man ist jedoch nicht darauf angewiesen. Es reicht vollkommen aus, die Klasse von der offiziellen PEAR-Seite zu downloaden und in das Projekt einzubinden.

[:en]Installation
If you’re using PEAR, simply use the pear installer.
[shell]
d:\php5> pear install Console_Getopt-1.3.0
[/shell]

But you don’t have to. It is sufficent to download the class here and include it into your project.

[:de]Anwendung
Die Anwendung ist denkbar einfach. Man bindet die Klasse in das eigene Programm ein, initialisiert das Klassenobjekt, definiert erlaubte Optionen und prüft dann die übergebenen Parameter.

Hier ein einfaches Beispiel zur Anwendung.

Beispiel 2: demo_getopt.php
[php]
<?php
// Klasse einbinden
include ("Getopt.php");

// Klasse initialisieren
$cg = new Console_Getopt();

/**
* Erlaubte Optionen:
* -a Abba
* -b Beatles
* -q Queen
*/
$allowedOptions = "abq";

// Kommandozeile lesen
$args = $cg->readPHPArgv();

// Optionen herausfiltern
$ret = $cg->getopt($args, $allowedOptions);

// Errorhinweis
if (PEAR::isError($ret)) {
die ("Fehler in Kommandozeile: " . $ret->getMessage() . "\n");
}

// Ausgabe der Optionen
print_r($ret);
?>
[/php]

Ausgabe zu Beispiel 2:
[shell]
d:\temp\getopt>php.exe demo_getopt.php -ab Who Genesis
Array
(
[0] => Array
(
[0] => Array
(
[0] => a
[1] =>
)

[1] => Array
(
[0] => b
[1] =>
)

)

[1] => Array
(
[0] => Who
[1] => Genesis
)

)

d:\temp\getopt>d:\php5\php.exe demo_getopt.php -c
Error in command line: Console_Getopt: unrecognized option — c
[/shell]

Nach dem Filtern der Optionen kann man nun die über die Kommandozeile eingebenen Parameter auswerten und weiter verarbeiten.

Beispiel 3: demo_getopt_erweitert.php
[php]
.
.
.
// Optionen herausfiltern
$ret = $cg->getopt($args, $allowedOptions);

$optionen = $ret[0];
if (sizeof($optionen) > 0) {
// mindestens eine Option wurde gewählt
foreach ($optionen as $o) {
switch ($o[0]) {
case ‚a‘:
echo "gewählte Band: Abba\n";
break;
case ‚b‘:
echo "gewählte Band: Beatles\n";
break;
case ‚q‘:
echo "gewählte Band: Queen\n";
break;
}
}
}
[/php]

Die Klasse kann noch mehr, unter anderem ist es z.B. möglich, notwendige und optionale Parameter definieren. Auch kann man definieren, ob Parameter Zeichenketten oder Zahlenwerte sein dürfen.

Wer einen tieferen Einblick in die Klasse möchte, die Klasse selbst ist gut dokumentiert. Einen ausführlichen und guten Artikel mit weiteren Anwendungsbeispielen gibt es hier bei Zend.

[:en]Usage
Not only installing this class is easy, so is the usage of it. Just include the class into your programm, initialize the class object, define allowed options and then check the parameters.

Here’s a simple example.

Beispiel 2: demo_getopt.php
[php]
<?php
// include class
include ("Getopt.php");

// initialize class
$cg = new Console_Getopt();

/**
* allowed options:
* -a Abba
* -b Beatles
* -q Queen
*/
$allowedOptions = "abq";

// read commandline
$args = $cg->readPHPArgv();

// filter options
$ret = $cg->getopt($args, $allowedOptions);

// error message
if (PEAR::isError($ret)) {
die ("error in commandline: " . $ret->getMessage() . "\n");
}

// print the options
print_r($ret);
?>
[/php]

Output Example 2:
[shell]
d:\temp\getopt>php.exe demo_getopt.php -ab Who Genesis
Array
(
[0] => Array
(
[0] => Array
(
[0] => a
[1] =>
)

[1] => Array
(
[0] => b
[1] =>
)

)

[1] => Array
(
[0] => Who
[1] => Genesis
)

)

d:\temp\getopt>d:\php5\php.exe demo_getopt.php -c
Error in command line: Console_Getopt: unrecognized option — c
[/shell]

After filtering the options you can now retrieve the command line parameters and work with them.

Example 3: demo_getopt_erweitert.php
[php]
.
.
.
// filter options
$ret = $cg->getopt($args, $allowedOptions);

$optionen = $ret[0];
if (sizeof($optionen) > 0) {
// at least one option has been used
foreach ($optionen as $o) {
switch ($o[0]) {
case ‚a‘:
echo "you choose: Abba\n";
break;
case ‚b‘:
echo "you choose: Beatles\n";
break;
case ‚q‘:
echo "you choose: Queen\n";
break;
}
}
}
[/php]

The class can do a few things more, for example it is possible to check for optional or necessary parameters, check for strings or numeric values and things like this.

If you want to take a closer look into the class, it is well documented. A more detailed article with a few more examples can be found here at Zend.


Beitrag veröffentlicht

in

,

von

Schlagwörter:

Kommentare

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.