• Stars
    star
    433
  • Rank 96,728 (Top 2 %)
  • Language
    PHP
  • License
    Other
  • Created over 12 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A powerful command line application framework for PHP. It's an extensible, flexible component, You can build your command-based application in seconds!

CLIFramework

Coverage Status Latest Stable Version Latest Unstable Version Total Downloads Monthly Downloads License

CLIFramework is a command-line application framework, for building flexiable, simple command-line applications.

Commands and Subcommands can be registered from outside of an application or your plugins.

Defining a new command is pretty simple, all you need to is declare a class which is inherited from CLIFramework\Command class.

Features

  • Intuitive command class and option spec

  • command options are supported, powered by GetOptionKit. including long option, short option, required|optional|default value.

  • Hierarchical commands.

  • Automatic help page generation.

  • Automatic zsh completion generator.

  • Automatic bash completion generator.

  • Friendly message when command arguments are not enough.

  • Testable, CLIFramework provides PHPUnit test case for testing the commands in PHP.

  • Argument validation, suggestion,

  • Command Groups

  • HHVM compatible

Synopsis

class CommitCommand extends CLIFramework\Command {

    public function brief() { return 'brief of bar'; }

    public function options($opts) {
        $opts->add('C|reuse-message:','Take an existing commit object, and reuse the log message and the authorship information (including the timestamp) when creating the commit.')
            ->isa('string')
            ->valueName('commit hash')
            // ->validValues([ 'static-50768ab', 'static-c2efdc2', 'static-ed5ba6a', 'static-cf0b1eb'])
            ->validValues(function() {
                $output = array();
                exec("git rev-list --abbrev-commit HEAD -n 20", $output);
                return $output;
            })
            ;

        // Runtime completion by setting up a closure for completion
        $opts->add('c|reedit-message:','like -C, but with -c the editor is invoked, so that the user can further edit the commit message.')
            ->isa('string')
            ->valueName('commit hash')
            ->validValues(function() {
                // exec("git log -n 10 --pretty=format:%H:%s", $output);
                exec("git log -n 10 --pretty=format:%H:%s", $output);
                return array_map(function($line) {
                    list($key,$val) = explode(':',$line);
                    $val = preg_replace('/\W/',' ', $val);
                    return array($key, $val);
                }, $output);
            })
            ;

        $opts->add('author:', 'Override the commit author. Specify an explicit author using the standard A U Thor <[email protected]> format.')
            ->suggestions(array( 'c9s', 'foo' , 'bar' ))
            ->valueName('author name')
            ;

        $opts->add('output:', 'Output file')
            ->isa('file')
            ;
    }

    public function arguments($args) {
        $args->add('user')
            ->validValues(['c9s','bar','foo']);

        // Static completion result
        $args->add('repo')
            ->validValues(['CLIFramework','GetOptionKit']);

        // Add an argument info expecting multiple *.php files
        $args->add('file')
            ->isa('file')
            ->glob('*.php')
            ->multiple()
            ;
    }

    public function init() {

        $this->command('foo'); // register App\Command\FooCommand automatically

        $this->command('bar', 'WhatEver\MyCommand\BarCommand');

        $this->commandGroup('General Commands', ['foo', 'bar']);

        $this->commandGroup('Database Commands', ['create-db', 'drop-db']);

        $this->commandGroup('More Commands', [
            'foo' => 'WhatEver\MyCommand\FooCommand',
            'bar' => 'WhatEver\MyCommand\BarCommand'
        ]);
    }

    public function execute($user,$repo) {
        $this->logger->notice('executing bar command.');
        $this->logger->info('info message');
        $this->logger->debug('info message');
        $this->logger->write('just write');
        $this->logger->writeln('just drop a line');
        $this->logger->newline();

        return "Return result as an API"; // This can be integrated in your web application
    }
}

Automatic Zsh Completion Generator

Imgur

Zsh Completion With Lazy Completion Values:

Imgur

Bash Completion

Imgur

Documentation

See documentation on our wiki https://github.com/c9s/CLIFramework/wiki

Command Forms

CLIFramework supports many command-line forms, for example:

$ app [app-opts] [subcommand1] [subcommand1-opts] [subcommand2] [subcommand2-opts] .... [arguments] 

If the subcommand is not defined, you can still use the simple form:

$ app [app-opts] [arguments]

For example,

$ app db schema --clean dbname
$ app gen controller --opt1 --opt2 ControllerName 

Subcommand Hierarchy

Commands have methods for stages, like prepare, execute, finish, for a command like below:

$ app foo_cmd bar_cmd arg1 arg2 arg3

The call graph is like:

app->run
- app->prepare
  - foo_cmd->prepare
    - bar_cmd->prepare
    - bar_cmd->execute
    - bar_cmd->finish
  - foo_cmd->finish
- app->finish

Basic Requirement

  • PHP 5.3

Installation

From composer

{
    "require": {
        "corneltek/cliframework": "*"
    }
}

Zsh Completion Generator

example/demo zsh demo > _demo
source _demo
demo <TAB>

Imgur

Imgur

Imgur

Imgur

Console Prompt (Readline)

simple prompt:

$input = $this->ask("Your name please");
$ php demo.php
Your name please: 

prompt and except valid values:

$input = $this->ask("Your name please", array('John', 'Pedro'));

Version Info

CLIFrameword has a built-in --version option, to setup the version info, you can simply override a const in your application class to setup version string:

class ConsoleApp extends CLIFramework\Application
{
    const NAME = 'YourApp';
    const VERSION = '1.2.1';
}

This shows:

$ yourapp.php --version
YourApp - version 1.2.1

Example

Please check example/demo.php

$ php example/demo.php

ArgumentEditor

use CLIFramework\ArgumentEditor\ArgumentEditor;

$editor = new ArgumentEditor(array('./configure','--enable-debug'));
$editor->append('--enable-zip');
$editor->append('--with-sqlite','--with-postgres');

echo $editor;
# ./configure --enable-debug --enable-zip --with-sqlite --with-postgres

Message style formatter

$formatter = new CLIFramework\Formatter;
$formatter->format( 'message' , 'green' );

Built-in styles:

'red'          => array('fg' => 'red'),
'green'        => array('fg' => 'green'),
'white'        => array('fg' => 'white'),
'yellow'       => array('fg' => 'yellow'),
'strong_red'   => array('fg' => 'red', 'bold'  => 1),
'strong_green' => array('fg' => 'green','bold' => 1),
'strong_white' => array('fg' => 'white','bold' => 1),

Building Phar Archive file

COMPOSER=tests/fixture/composer.json.phar-test composer install
php example/demo archive --working-dir /Users/c9s/work/php/CLIFramework \
        --composer tests/fixture/composer.json.phar-test \
        app.phar

Chooser Component

$chooser = new CLIFramework\Chooser;
$value = $chooser->choose( "System Options" , array( 
    'use php-5.4.0' => '5.4.0',
    'use php-5.4.1' => '5.4.1',
    'use system' => '5.3.0',
));

Debug Utilities

LineIndicator

use CLIFramework\Debug\LineIndicator;
$indicator = new LineIndicator;
echo PHP_EOL, $indicator->indicateFile(__FILE__, __LINE__);

ConsoleDebug class

use CLIFramework\Debug\ConsoleDebug;

ConsoleDebug::dumpRows($pdo->fetchAll());

ConsoleDebug::dumpException($e);

Todos in the next release

  • provide a easy way to define chained commands
  • inheritable options for subcommands.
  • human readable exception renderer.
  • interact utilities

Hacking

Setup

  1. Download & install Onion from https://github.com/phpbrew/Onion

  2. Use Onion to bundle the dependencies:

    $ onion bundle

  3. Run tests, it should pass.

  4. Hack hack hack.

  5. Run tests.

  6. Send a pull request.

How command class register works

  • CLIApplication is inherited from CommandBase.
  • Command is also inherited from CommandBase.
  • To register a subcommand, we use the addCommand method to register commands or subcommands.
    • The command class is optional, if command class name is omitted, then the addCommand method will try to guess the real command class, and try to load the command class.

Bitdeli Badge

More Repositories

1

Pux

Pux is a fast PHP Router and includes out-of-box controller tools
C
1,272
star
2

bbgo

The modern cryptocurrency trading bot framework written in Go.
Go
1,100
star
3

r3

libr3 is a high-performance path dispatching library. It compiles your route paths into a prefix tree (trie). By using the constructed prefix trie in the start-up time, you may dispatch your routes with efficiency
C
799
star
4

goprocinfo

Linux /proc info parser for Go
Go
725
star
5

c6

Compile SASS Faster ! C6 is a SASS-compatible compiler
Go
430
star
6

gomon

Monitor for any changes in your go package and automatically restart commands (run, build, server or anything)
Go
210
star
7

vikube.vim

Operating Kubernetes Cluster from Vim, in Vim
Vim Script
195
star
8

Vimana

Vimana is an easy to use system for searching , installing, and downloading vim script. Vimana provides a command-line interface such like aptitude programe on Debian linux, for you to search , download , install , upgrade scripts from http://www.vim.org (vimonline site).
Perl
182
star
9

guts

Guts is a new language beyonds PHP.
Go
155
star
10

GetOptionKit

An object-oriented option parser library for PHP, which supports type constraints, flag, multiple flag, multiple values, required value checking
PHP
144
star
11

SQLBuilder

A powerful, fast, cross-platform SQL Builder for PHP. Convert your structured data into SQL queries with a fluent style interface and targeting on all the mainstream database (MySQL, PostgreSQL, SQLite)
PHP
142
star
12

h3

The Fast HTTP header parser library
C
130
star
13

perlomni.vim

perl omnicompletion for vim (including base class function compleltions .. etc)
Vim Script
128
star
14

github-taiwan

Taiwan Developers on Github
Perl
117
star
15

Roller

A simple, fast router for PHP5.3/4, support APC cache, RESTful, highly extendable and flexible.
PHP
86
star
16

hypergit.vim

This git plugin provides many awesome features so that you don't need to type commands anymore..
Vim Script
61
star
17

App-gh

GitHub Command-line Utility.
Perl
53
star
18

AssetKit

A Modular Asset Toolkit for PHP Applications
HTML
52
star
19

fsrename

FSRename V2 - A simple, powerful rename tool supports complex filtering
Go
51
star
20

xarray

The missing PHP array functions you are looking for, implemented in extension
C
41
star
21

ts-webpack-starter

Template project based on TypeScript, Typings, Babel and Webpack
JavaScript
41
star
22

GenPHP

A Powerful,Flexible Code Generator for PHP, can generate anything what you want for your project.
PHP
40
star
23

CodeGen

Transform your dynamic calls to static calls!
PHP
37
star
24

PHPRelease

PHPRelease manages your package release process.
PHP
32
star
25

cpan.vim

vim plugin for perl hackers. for you to search installed module/all modules and integrated with perldoc window
Vim Script
29
star
26

requestgen

request builder generator for Go!
Go
28
star
27

Plack-Middleware-OAuth

Plack Middleware for OAuth1 and OAuth2
Perl
27
star
28

goenv

Go project environment builder - build isolated workspace for your go project
27
star
29

php-ext-skeleton

The minimal PHP extension skeleton
C
27
star
30

reducer

Fast Map & Reduce php7 extension for large array
C
26
star
31

phpunit.vim

phpunit plugin for Vim editor
Vim Script
25
star
32

vim-dev-plugin

A Vim plugin for developing VimL.
Vim Script
25
star
33

vim-makefile

A lightweight non-dependency Makefile for install, uninstall, bundle, distribute Vim plugin scripts.
Vim Script
24
star
34

GoTray

Go application manager in your system status bar. (for Mac OS X)
24
star
35

typeloy

typeloy is a meteor application deployment tool written in typescript.
TypeScript
24
star
36

gsession.vim

gsession.vim saves your session files into the same directory (~/.vim/session/) by default. and auto-detect your session file to load session file when you are opening vim editor without arguments.
Vim Script
24
star
37

callbackgen

callbackgen generates callback pattern for your callback fields.
Go
23
star
38

cpansearch

CPAN module search in C.
C
23
star
39

FastCommit

Integrating GIT commit flow with your own editor easily!
23
star
40

zh-stroke-data

ๅธธ็”จๅœ‹ๅญ—ๆจ™ๆบ–ๅญ—้ซ”็ญ†ๅŠƒ XML ่ณ‡ๆ–™ๆช”
JavaScript
22
star
41

gatsby

Gatsby Database Toolkit For Go (ORM, SQL Builder and SQLUtils)
Go
20
star
42

SimpleBench

SimpleBench provides suckless benchmark tools for PHP5.3
PHP
20
star
43

WebUI

Abstract PHP interface for building common HTML components with microdata
PHP
20
star
44

WireRoom

Collaborative Chatroom For Hackers
JavaScript
19
star
45

markdown-git-wiki

This is a pure git wiki (not a web server or web app), this utility only provides the functionbility of translating markdown pages into web pages. links between pages can be named by "[[Link]]". so your git wiki is just a git repository.
Perl
19
star
46

LazyBone

MicroFramework: LazyRecord + BackBone + Roller RESTful Router
JavaScript
18
star
47

gitorbit

GitHub-like Git Server, let you control the permission via mongodb or LDAP
Go
17
star
48

jira.sh

JIRA Client for Bash Scripts
Shell
17
star
49

perldoc-zhtw-translation

Perldoc Translation in zh-tw
Perl
17
star
50

php-r3

high performance r3 router extension for PHP
C
17
star
51

colorselector.vim

provide emacs-like colorscheme selector buffer.
Makefile
17
star
52

ClassMap

Generate class mapping file in PHP, to improve classloader performance.
PHP
16
star
53

jchash

Jump Consistent Hashing Algorithm implemented in PHP 7 Extension
C
15
star
54

router-benchmark

PHP Router Benchmark
PHP
14
star
55

go-aes-crypt

Go
13
star
56

php-FastRequire

SPL class loader is slow! Now you can skip the SPL functions to load your minimal class requirements directly.
13
star
57

GrindKit

PHP GrindKit for reading cachegrind compatible file.
PHP
13
star
58

MiniPear

MiniPear creates local pear channel mirrors for offline usage.
PHP
12
star
59

simple-commenter.vim

simple commenter plugin
Vim Script
11
star
60

cascading.vim

Vim Script
11
star
61

rockhopper

rockhopper is an embeddable migration tool written by Go
Go
11
star
62

ConfigKit

Toolkit for Config Files, use fast but readable YAML config file for your PHP project.
PHP
11
star
63

ClassTemplate

Class template for PHP
PHP
11
star
64

umobi

ยตMobi - Micro Mobile Web Framework for Smartphones & Tablets.
JavaScript
10
star
65

xfile

PHP Extension for file operations
C
9
star
66

PJSON

PJSONEncoder implements a JSON encoder with PHP object to JavaScript object translation support.
PHP
9
star
67

Git-Release

A Git Release Manager
Perl
8
star
68

ZLogger

A Simple Logger for PHP based on ZeroMQ
PHP
8
star
69

perl-poppler

basic porting of poppler
Perl
8
star
70

lftp-sync.vim

lftp sync plugin for vim.
Vim Script
8
star
71

vimomni.vim

a better completion for VimL.
Vim Script
8
star
72

kubernetes-term

Connecting xterm.js to kubernetes exec spdy stream with socket.io
Go
8
star
73

phpkmp

Knuth-Morris-Pratt algorithm implemented in C, PHP and PHP Extension
C
8
star
74

PerlTW-Planet

Perl Taiwan Planet
CSS
8
star
75

inflect

Inflector for Go
Go
7
star
76

vagrant-kubeadm

Vagrant for kubeadm
Shell
7
star
77

chrome-extension-template

7
star
78

bufexplorer

Vim Script
7
star
79

more.vim

ไธ€็”จๅฐฑๆ„›ไธŠ็š„ไธญๆ–‡ๅ‡ๆ–‡็”ข็”Ÿๅ™จไน‹ Vim Plugin
Vim Script
7
star
80

sid

Sequential ID generator as a micro-service, implemented in Go
Go
7
star
81

d3-kmeans

A simple, lightweight, single-dimension k-means clustering algorithm implemented in javascript for d3.
JavaScript
7
star
82

alpine-dlib

base image for dlib application
Shell
7
star
83

Kendo

The Powerful Access Control Framework
PHP
7
star
84

CacheKit

Generic cache interface for FileSystem cache, Memcached, ApcCache, ... etc
PHP
7
star
85

requestgen-tutorial

Go
7
star
86

universal

The general purpose standard library for PHP.
PHP
7
star
87

PHPUnit_TestMore

let you define Test::More-like unit tests and base on the great PHPUnit testing framework.
PHP
7
star
88

CurlKit

A tiny curl based library for managing request/response/download task.
PHP
7
star
89

glusterfs-deploy

Shell
6
star
90

taipei.pm

Taipei.pm
Perl
6
star
91

ssh-authorizedkey

AuthorizedKey Encoder implemented in Go
Go
6
star
92

action-js

The powerful javascript library for connecting form components with backend protocols.
JavaScript
6
star
93

zhwrap.vim

Chinese text wrapping vim plugin.
Vim Script
6
star
94

c9s

6
star
95

go-duck

Duck Typing for Go
Go
6
star
96

OAuthProvider

PHP
6
star
97

php-fileutil

Fast File Utility Functions in PHP Extension and Pure PHP.
C
6
star
98

cssmin

Fast & Simple CSS Minify C extension for PHP
C
6
star
99

VersionKit

Version String Utilities
PHP
6
star
100

dlib-serving

Run dlib model inference as a gRPC server
CMake
6
star