Download the PHP package alexp007/cli without Composer

On this page you can find all versions of the php package alexp007/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 cli

PHP CLI APP

documentation:

English

Simple and easy library for rapid development of command line applications in php.

Php version> = 7.1

Installation

composer require --prefer-dist alexp007/cli

Fast start

Remember to include composer autoloader, like this:

require __DIR__ . "/../vendor/autoload.php"; // path to autoload.php

then

use Cli\Basic\Cli;

Cli::initialize([
    'script_file_name' => 'cli.php' // название файла
]);

Cli::handle('sayHi', function ($name) { // callable 
    return "hi " . $name; 
});

Cli::run();

now command can be used via cli:

php cli.php sayHi pete

the result of the execution will be:

hi pete

Creating commands

You can create any number of commands using:

Cli::handle($commandName, $callable)

Extended syntax looks like this:

Cli::handle(string $command, callable $callback, array $flags = array(), array $env = array())

Extended command declaration example:

use Cli\Basic\Cli;
use Cli\Basic\Flags;
use Cli\Basic\Environment;

Cli::handle('sayHi', function ($name, Flags $flags, Environment $env) { // callable
    if ($flags->getFlag('--send')) {
        return "mail sent to administrator" . $env->getEnv('email');  
    }
    return "hi " . $name;
}, ['--send'], ['email' => '[email protected]']);

If you want to use Flags and Environment, then specifying the data type in the arguments is mandatory.

This library strictly refers to the arguments of commands, which means a command that expects a single argument cannot be called without it. However, if the argument is optional, then when creating the function, you should specify the default value for the argument null, for example:

Cli::handle('sayHi', function ($name = null) {
    return 'hi';
});

If you expect a variable number of arguments, then you are prompted to use a Params object:

use Cli\Basic\Cli;
use Cli\Basic\Params;

Cli::handle('bit', function(Params $params){
    $allParams = $params->getArray();
    return join(',', $allParams);
});

When using special objects (Params, Flags, Environment) as arguments, their order does not matter:

use Cli\Basic\Cli;
use Cli\Basic\Flags;
use Cli\Basic\Params;
use Cli\Basic\Environment;

Cli::handle('sayHi', function (Flags $flags, Environment $env, Params $params) { // callable
   return $params;
}, ['--send'], ['email' => '[email protected]']);

Any other arguments should be specified before special ones.

Fundamental rules

Special Objects

Params

Params::getParam(int $n) - where $n is position
Params::getArray(): array // all params

Flags

Flags::getFlag(string $flag)
Flags::getArray(): array // all flags

Environment

Environment::getEnv(string $key)
Environment::getArray(): array // all environment vars

Configuration

When initializing the application, you can set configuration settings, here is an example:

Cli::initialize([
    'script_file_name'            => 'cli.php',
    'enable_list'                 => 'on',
    'enable_exceptions'           => 'on',
    'enable_errors'               => 'on',
    'enable_find_command_package' => 'on',
]); 

You could set global variables by passing them as the second parameter. They will be available within special object Environment inside commands

Aliases

When passing environment variables, you can use aliases using the @ special character. The alias will be interpolated within the string, for example:

Cli::initialize([
        'script_file_name' => 'cli.php',
    ], [
        'object' => 'ufo',
        'article_name' => '@object is flying in the sky'
    ]);

The article_name value will be: "ufo is flying in th sky"

Built-in Commands

list (if 'enable_list' => 'on') allows you to use the built-in list command, which lists all teams registered in the system and brief information about them:

php cli.php list

will return:

+-------------+---------------+------------------+
| Command     | Params        | Flags            |
+-------------+---------------+------------------+
| bit         |               |                  |
| find:file   | path, pattern | -r               |
| find:inFile | path, pattern | -r, --extensions |
| list        |               |                  |
| sayHi       |               | --send           |
| table       |               |                  |
+-------------+---------------+------------------+

find:file [path to the search directory] [pattern - regular expression] -> search for files in the system.

You can use the "-r" flag to recursively search subdirectories:

php cli.php find:file ./ "php"

will find files with php extension:

+--------------+----------------+
| Filename     | Filepath       |
+--------------+----------------+
| autoload.php | ./autoload.php |
| cli.php      | ./cli.php      |
+--------------+----------------+

find:inFile [path to the search directory] [pattern - regular expression] -> search for matches in files.

You can use the -r flag to recursively search subdirectories and the “--extensions” flag indicates the exact extensions, separated by commas (only these files will be searched):

php cli.php find:inFile --extensions=php ./ "include"

will return

+--------------------------------+------+----------+-----------+
| Match                          | Line | Filename | Filepath  |
+--------------------------------+------+----------+-----------+
| include_once "src/$class.php"; | 12   | cli.php  | ./cli.php |
+--------------------------------+------+----------+-----------+

To use the find package commands, you need to set 'enable_find_command_package' => 'on' in the configuration.

Formatter

A class that simplifies the work with outputting the result:

use Cli\Basic\Formatter;

Output color red:

Formatter::red() : $this

Output color blue:

Formatter::blue() : $this

Output color red:

Formatter::yellow() : $this

Table view:

Formatter::asTable(): $this

Line break:

Formatter::line() : $this

Prints to output stream:

Formatter::printOut()

Creating a new Formatter (you can pass an array or a string):

new Formatter(array or string $data)

Special objects (Params, Flags, Environment) can be passed without additional adaptation:

use Cli\Basic\Cli;
use Cli\Basic\Formatter;

Cli::handle('bit', function(Params $params){
    $fmt = new Formatter($params);
    return $fmt->blue();
});

Example table output:

use Cli\Basic\Cli;
use Cli\Basic\Formatter;

Cli::handle('table', function() {
    $data = [
        ['command_1', 'params', 'flags'],
        ['command_2', '[1,34,56,]', '[-f -r -d]'],
        ['special_command', '[1,string,56,]', '[-f -r -d]'],
    ];

    $fmt = new Formatter($data);
    return $fmt->asTable()->red();

});

Successful development to you!

Write to me with any questions or suggestions to [email protected], as well as create issues.

Contributors welcome!

Russian

Простая и легкая библиотека для скоростной разработки приложений командной строки на php.

Версия php >= 7.1

Установка

composer require --prefer-dist alexp007/cli

Быстрый старт

Не забудьте подключить автозагрузчик composer, например так:

require __DIR__ . "/../vendor/autoload.php"; // путь до автозагрузчика

далее

use Cli\Basic\Cli;

Cli::initialize([
    'script_file_name' => 'cli.php' // название файла
]);

Cli::handle('sayHi', function ($name) { // callable 
    return "hi " . $name; 
});

Cli::run();

затем можно использовать в командной строке:

php cli.php sayHi pete

результат выполнения будет:

hi pete

Создание команд

Вы можете создавать любое кол-во команд используя:

Cli::handle($commandName, $callable)

Расширенный синтаксис выглядит так:

Cli::handle(string $command, callable $callback, array $flags = array(), array $env = array())

Расширенное создание команды может выглядеть так:

use Cli\Basic\Cli;
use Cli\Basic\Flags;
use Cli\Basic\Environment;

Cli::handle('sayHi', function ($name, Flags $flags, Environment $env) { // callable
    if ($flags->getFlag('--send')) {
        return "mail sent to administrator" . $env->getEnv('email');  
    }
    return "hi " . $name;
}, ['--send'], ['email' => '[email protected]']);

Если вы хотите использовать Flags и Environment, то указание типа данных в агрументах обязательно.

Данная библиотека строго относится к аргументам команд, что значит команду, ожидающую один аргумент, нельзя будет вызвать без него. Однако, если аргумент не обязательный, то при создании функции следует указать значение по умолчанию для аргумента null, например:

Cli::handle('sayHi', function ($name = null) {
    return 'hi';
});

Если вы ожидаете переменное число аргументов, то предлается использовать объект Params:

use Cli\Basic\Cli;
use Cli\Basic\Params;

Cli::handle('bit', function(Params $params){
    $allParams = $params->getArray();
    return join(',', $allParams);
});

При использовании специальных объектов (Params, Flags, Environment) в качестве аргументов, их порядок не имеет значений:

use Cli\Basic\Cli;
use Cli\Basic\Flags;
use Cli\Basic\Params;
use Cli\Basic\Environment;

Cli::handle('sayHi', function (Flags $flags, Environment $env, Params $params) { // callable
   return $params;
}, ['--send'], ['email' => '[email protected]']);

Любые обычные аргументы следует указывать до специальных.

Основные правила

Специальные объекты

Params

Params::getParam(int $n) - where $n is position
Params::getArray(): array // all params

Flags

Flags::getFlag(string $flag)
Flags::getArray(): array // all flags

Environment

Environment::getEnv(string $key)
Environment::getArray(): array // all environment vars

Конфигурация

При инициализации приложения можно передавать настройки параметров конфигурации, вот пример использования всех настроек:

Cli::initialize([
    'script_file_name'            => 'cli.php',
    'enable_list'                 => 'on',
    'enable_exceptions'           => 'on',
    'enable_errors'               => 'on',
    'enable_find_command_package' => 'on',
]);

Так же поддерживает возможность передачи глобальныч переменных вторым параметром, которые будут доступны в специальном объекте Environment внутри команд:

   Cli::initialize([
           'script_file_name' => 'cli.php',
        ], [
           'custom_var' => 'value' // любые типы данных
        ]
   );

Псевдонимы

При передачи переменных окружения вы можете использовать псевдонимы при помощи специального символа @. Псевдоним будет интерполирован внутри строки, например:

Cli::initialize([
    'script_file_name' => 'cli.php',
], [
    'object' => 'ufo',
    'article_name' => '@object is flying in the sky'
]);

Значение article_name будет: "ufo is flying in th sky"

Встроенные команды

list (если 'enable_list' => 'on') позволяет использовать встроенную команду list, которая выводит список всех зарегистрированных в системе команд и краткую информацию о них:

php cli.php list

вернет:

+-------------+---------------+------------------+
| Command     | Params        | Flags            |
+-------------+---------------+------------------+
| bit         |               |                  |
| find:file   | path, pattern | -r               |
| find:inFile | path, pattern | -r, --extensions |
| list        |               |                  |
| sayHi       |               | --send           |
| table       |               |                  |
+-------------+---------------+------------------+

find:file [путь к директории поиска] [паттерн - регулярное выражение] -> поиск файлов в системе.

Можно использовать флаг "-r" для рекурсивного поиска в поддиректориях:

php cli.php find:file ./ "php"

найдет файлы c расширением php:

+--------------+----------------+
| Filename     | Filepath       |
+--------------+----------------+
| autoload.php | ./autoload.php |
| cli.php      | ./cli.php      |
+--------------+----------------+

find:inFile [путь к директории поиска] [паттерн - регулярное выражение] -> поиск совпадений внутри файлов.

Можно использовать флаг "-r" для рекурсивного поиска в поддиректориях и флаг "--extensions" для указания точных расширений, через запятую (только для этих файлов будет произведен поиск):

php cli.php find:inFile --extensions=php ./ "include"

вернет:

+--------------------------------+------+----------+-----------+
| Match                          | Line | Filename | Filepath  |
+--------------------------------+------+----------+-----------+
| include_once "src/$class.php"; | 12   | cli.php  | ./cli.php |
+--------------------------------+------+----------+-----------+

Для использования команд пакета find нужно в конфигурации установить 'enable_find_command_package' => 'on'.

Formatter

Класс, который упрощает работу с выводом результата:

use Cli\Basic\Formatter;

Цвет вывода красный:

Formatter::red() : $this

Цвет вывода синий:

Formatter::blue() : $this

Цвет вывода красный:

Formatter::yellow() : $this

Табличное представление:

Formatter::asTable(): $this

Перенос строки:

Formatter::line() : $this

Печатает в поток вывода:

Formatter::printOut()

Создание нового Formatter(можно передавать массив или строку):

new Formatter(array or string $data)

Специальные объекты (Params, Flags, Environment) можно передавать без обработки:

use Cli\Basic\Cli;
use Cli\Basic\Formatter;

Cli::handle('bit', function(Params $params){
    $fmt = new Formatter($params);
    return $fmt->blue();
});

Пример табличного вывода:

    use Cli\Basic\Cli;
    use Cli\Basic\Formatter;

    Cli::handle('table', function() {
        $data = [
            ['command_1', 'params', 'flags'],
            ['command_2', '[1,34,56,]', '[-f -r -d]'],
            ['special_command', '[1,string,56,]', '[-f -r -d]'],
        ];

        $fmt = new Formatter($data);
        return $fmt->asTable()->red();

    });

Успешной вам разработки!

Пишете мне с любыми вопросами и предложениями на [email protected], а так же создавайте issues.

Всем желающим контрибьютить - добро пожаловать!


All versions of cli with dependencies

PHP Build Version
Package Version
Requires php Version ^7.1
ext-mbstring Version *
ext-json Version *
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 alexp007/cli contains the following files

Loading the files please wait ....