Download the PHP package vanilla/garden-cli without Composer

On this page you can find all versions of the php package vanilla/garden-cli. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package garden-cli

Garden CLI

Build Status Packagist Version MIT License CLA

Introduction

Garden CLI is a PHP command line interface library meant to provide a full set of functionality with a clean and simple api.

Why use Garden CLI?

PHP's getopt() provides little functionality and is prone to failure where one typo in your command line options can wreck and entire command call. Garden CLI solves this problem and provides additional functionality.

Installation

Garden CLI requires PHP 8.1 or higher

Garden CLI is PSR-4 compliant and can be installed using composer. Just add vanilla/garden-cli to your composer.json.

Defining The CLI

The Cli class provides a fluent interface for defining commands, opts, and args.

Basic Example

Here is a basic example of a command line script that uses Garden CLI to parse its options. Let's say you are writing a script called dbdump.php to dump some data from your database.

This example returns an Args object or exits to show help or an error message. Here are some things to note about the example.

Option Types

The opt method has a $type parameter that you can use to specify a type for the option. The valid types are integer, string, and boolean with string as the default.

You can also add [] after the type name to specify an array. To supply an array on the command line you specify the option multiple times like so:

Displaying Help

If you were to call the basic example with a --help option then you'd see the following help printed:

usage: dbdump.php [<options>]

Dump some information from your database.

OPTIONS
  --database, -d   The name of the database to dump.
  --help, -?       Display this help.
  --host, -h       Connect to host.
  --password, -p   Password to use when connecting to server.
  --port, -P       Port number to use.
  --user, -u       User for login if not current user.

All of the options are printed in a compact table and required options are printed in bold. The table will automatically expand to accommodate longer option names and wrap if you provide extra long descriptions.

Displaying Errors

Let's say you call the basic example with just -P foo. What you'd see is the following error message:

The value of --port (-P) is not a valid integer.
Missing required option: database
Missing required option: user

Using the Parsed Options

Once you've successfully parsed the $argv using Cli->parse($argv) you can use the various methods on the returned Args object.

Multiple Commands Example

Let's say you are writing a git-like command line utility called nit.php that pushes and pulls information from a remote repository.

Like the basic example, parse() will return a Args object on a successful parse. Here are some things to note about this example.

Listing Commands

Calling a script that has commands with no options or just the --help option will display a list of commands. Here is the output from the multiple commands example above.

usage: nit.php <command> [<options>] [<args>]

COMMANDS
  push   Push data to a remote server.
  pull   Pull data from a remote server.

Args and Opts

The Args class differentiates between args and opts. There are methods to access both opts and args on that class.

The CliApplication Class

The basic Cli class works well for defining and documenting opts and args. However, you still need to wire up the parsed command line args to your own code. If you want to reduce this boilerplate, you can use the CliApplication class.

Note: In order to use the CliApplication functionality you will need to require some extra dependencies. See the suggested packages in composer.json for more information.

Defining a Subclass of CliApplication

To use the CliApplication you usually subclass it and override the configureContainer() and configureCli() methods to define the commands in your app.

This example wires up three methods.

Using the addMethod() Method

You can wire up class methods to the command line by using addMethod(). This does the following:

  1. It will create a command derived from the method name. Override the command name with the OPT_COMMAND option.
  2. It will optionally create opts for object setters. Object setters are methods that start with the word set and take one argument. You can opt out of setter wiring with the OPT_SETTERS options.
  3. It will create opts for method parameters. If the method has class type-hinted types they will not be wired up to opts, but instead will be satisfied with the container.
  4. It will use method doc blocks to add descriptions for the command and opts. Make sure you use PHPDoc syntax.

You can call addMethod() with either a static or instance method. If you pass a static method then it will only wire up static setters. An instance method will wire up both static and instance methods.

Using the addCommandClass() Method

The addCommanClass() method is very similar to adMethod() except for the following:

  1. The command name will be inferred from the class name. You can use the OPT_COMMAND_REGEX to strip out a prefix or suffix. By default the regex will strip a suffix for classes that end in "Job" or "Command".
  2. It will infer the command description from the class description.
  3. Opts are created from setters by default.

Using the addCallable() Method

You can wire up an ad-hoc closure to the command line by using addCallable(). This works much like addMethod(), but will only reflect the callable's parameters.

Even though it's not a common practice to add a doc block to an inline closure, you can do so and it will be used to document the command. If you don't do so, but at least want a description then use the OPT_DESCRIPTION option to provide one.

Using the addConstructor() and addFactory() Methods

You can add dependencies by wiring up their constructor parameters or a factory method to the opts. The most common use case is specifying connection parameters to a database or an access token to an API client.

Use addConstructor() if the class has constructor parameters that make sense coming from the command line.

Use addFactory() if you want to clean up the names of the parameters or do some additional properties somehow.

If the constructor or factory has class type hints then not to worry. Those will be auto-wired through the container. You can then configure them through the container directory or even wire them up to opts by making additional calls to addConstructor() or addFactory().

Using the addCall() Method

You can wire up a call to a class method using the addCall() method. Use this for setter injection. The call will be applied when the class is instantiated.

Running Your Application

To use your application you just need to call the main() method.

The main method does the following:

  1. Parses the $argv parameter to determine the command.
  2. If the command maps to an instance method then an instance is fetched from the container.
  3. Setters are applied from the opts.
  4. The method is invoked through the container, satisfying any arguments that were not specified as opts.

Migrating from a Garden CLI application to a CliApplication

If you want to migrate an older Garden CLI application to a CliApplication then you want to do the following:

  1. Replace your use of the Cli class with CliApplication. The CliApplication is a subclass of the main Cli class. So if you have an application that uses the Cli class then you can just replace your instance to the CliApplication and use your old code.

  2. Override the CliApplication::dispatchInternal() method and move your switch statement or whatever there. Make sure to call parent::dispatchInternal() after your code, usually as the default of your switch.

  3. Replace your call to $cli->parse($argv) with a call to $cli->main($argv). This will parse the arguments and dispatch to your dispatchInternal() method.

  4. Now you can start replacing some of your boilerplate with calls to the CliApplication specific methods. You can leave your old boilerplate as is and just use the CliApplication helpers for new code if you'd like.

Logging

Many CLI applications require some form of logging. Garden CLI has you covered.

Formatting Output with the TaskLogger

The TaskLogger is a PSR-3 log decorator helps you output task-based information to the console in a nice, compact style. It's good for things like install scripts, scripts that take a long time, or scripts you put into a cron job.

Logging Tasks

When using the TaskLogger you want to think in terms of messages and tasks. A message is a single log item to output to the user. A task has a begin and an end and can be nested as much as you want. Messages are output using the various PSR-3 methods while tasks are output with begin() and end(). Here are all of the methods you can use to log tasks.

Method Notes
begin Log the beginning of a task.
beginDebug, beginInfo, beginNotice, beginWarning, beginError, beginCritical, beginAlert, beginEmergency Log the beginning of a task with the given log level.
end Log the end of a task with the same level as it began.
endError Log the end of a task that resulted in an error.
endHttpStatus Log the end of a task with an HTTP status. The log level is calculated from the number of the status.

Task Nesting and Durations

You can nest tasks as much as you wish by calling a begin* method before calling an end* method. Each time you nest a task it will output its messages indented another level. Tasks also calculate their duration and output it at after the call to end.

Suppressing Messages

By default, the TaskLogger will only output messages that are at a level of LogLevel::INFO or higher. You can change this with the setMinLevel method. If you begin a task at a level that us suppressed, but a child message is at or above the min level then the begin task message will be output retroactively. This allows you to see what task kicked off the logged message.

Example

The StreamLogger

If you create and use a TaskLogger object it will output nicely to the console out of the box. Under the hood it is using a StreamLogger object to handle the formatting of the tasks to an output stream, in this case stdout. You can replace or modify the StreamLogger if you want to control logging in a more granular level. Here are some options.

Method Default Notes
setLineFormat '[{time}] {message}' Set the format of lines. Use the {level}, {time}, {message} strings to move the components around.
setColorizeOutput automatic Whether or not to use console colors.
setBufferBegins true Attempt to put task begin/end messages on the same line. Turn this off if you plan on writing to the log concurrently.
setTimeFormat '%F %T' Set the time format. This can be a strftime string or a callback.
setLevelFormat nothing Set a callback to format a LogLevel constant.

Example

The following example creates a StreamLogger object and tweaks some of its settings before passing it into the TaskLogger constructor.

Implementing Your Own Logger

You can give the TaskLogger any PSR-3 compliant logger and it will send its output to it. In order to use some of the special task functionality, you'll have to inspect the $contenxt argument of your log method. Here the fields that you may receive.

Field Type Notes
TaskLogger::FIELD_TIME int The timestamp of the message.
TaskLogger::FIELD_INDENT int The indent level of the message.
TaskLogger::FIELD_BEGIN bool True if the message denotes the beginning of a task.
TaskLogger::FIELD_END bool True if the message denotes the end of a task.
TaskLogger::FIELD_DURATION float The duration of a task in seconds and milliseconds.

All versions of garden-cli with dependencies

PHP Build Version
Package Version
Requires php Version >=8.1
ext-json Version *
psr/log Version ^3.0
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package vanilla/garden-cli contains the following files

Loading the files please wait ....