Question

I commonly use argparse module in Python to detect options/parameters, print usage, etc. I am trying to get the same results in PHP from native code or using some lightweight library/framework without writing a lot of wrapping lines.

From my research, I've just found getop()'s native PHP implementation, that is quite like getop()'s C implementation and very limited as a framework for certain uses (exclusive options, prefix options, parameter conflict handler, choices, metavars, etc). I would like to find an easy way to get the same results in PHP without using raw argv, reinventing the wheel or implementing "yet another improved library for getop()" to parse arguments.

This is how the argparse example looks in Python:

from argparse import ArgumentParser, ONE_OR_MORE, ArgumentDefaultsHelpFormatter

__version__ = '3.14'
description = 'some description'

parser = ArgumentParser(
                         prog                  = 'someprogram',
                         description           = description,
                         epilog                = None,
                         parents               = [],
                         formatter_class       = ArgumentDefaultsHelpFormatter,
                         prefix_chars          = '-',
                         fromfile_prefix_chars = None,
                         argument_default      = None,
                         conflict_handler      = 'error',
                         add_help              = True,
                        )

parser.add_argument('-o', '--output',
                    action         = 'store',
                    metavar        = '/path/to/output',
                    dest           = 'output',
                    choices       = None,
                    help           = 'Set the output directory')

parser.add_argument('-q', '--quiet',
                    action         = 'store_true',
                    dest           = 'quiet', 
                    default        = False,
                    help           = 'Don\'t print status messages to stdout')

parser.add_argument(option_strings = ['FILES'], 
                    metavar        = 'FILES', 
                    nargs          = ONE_OR_MORE,
                    type=str,
                    dest           = 'FILES',
                    help           = 'One or more files to process')

parser.add_argument('-v', '--version', 
                    action  ='version',
                    version ='%(prog)s {version}'.format(version = __version__),
                    help    = 'Shows the program version')

args = parser.parse_args()

In PHP you can translate the same behaviour but you need a lot of lines to fully emulate an argument parser like Python's.

PS: Please, don't take this question as python vs php, I could be the same ruby vs php, java vs php or other. It is just about how porting code well and efficient in another different language using native libs.

Was it helpful?

Solution

I just found a nearly aproximation to python argparse library. The php library Getopt.PHP partialy emulates a parser with several features and same behaviour in argparse.

For example add_options() ~= addOptions() method with positional or required arguments, automatic usage generation, retrieval values, error handling, etc.

At this moment, it still needs some work for more advanced features like conflict handler, choices or metavar, parse known values only, parameter exclusion, nargs, etc. But I can easily extended or use it as good implementation base start.

The Python example code in my question could be nearly translated (with missing features) to:

$getopt = new Getopt;
$getopt->addOptions(array(
    array('o', 'output', Getopt::OPTIONAL_ARGUMENT, 'Set the output directory'),
    array('q', 'quiet', Getopt::OPTIONAL_ARGUMENT, 'Don\'t print status messages to stdout'),
    array('v', 'version', Getopt::OPTIONAL_ARGUMENT, 'Shows the program version'),
    array('FILES', NULL, Getopt::REQUIRED_ARGUMENT),
));

$getopt->parse();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top