📜 ⬆️ ⬇️

Console commands with PHPixie Console

image PHPixie Console is a new component that allows you to create, route and run console commands. Like other framework libraries, it can easily be used without PHPixie itself as a simpler alternative to a similar library from symfony. First of all, this article is designed for those who already use PHPixie and it will contain a short description of the standard framework commands, but in the end I will also give an example of how to run PHPixie Console separately.

Upgrade existing projects
If you already have a PHPixie project, then for the Console to work you need to make a few simple changes:

  1. Copy https://github.com/PHPixie/Project/blob/master/console to the project root. If you are on Linux then put execution rights on this file (chmod + x console)
  2. Add "phpixie / framework-bundle": "~ 3.0" in composer.json
  3. Switch on \ PHPixie \ FrameworkBundle and add / * GeneratorPlaceholder * /
    like this: https://github.com/PHPixie/Project/blob/master/src/Project/Framework/Bundles.php

Optionally, you can also copy the standard architecture and demo team from the updated project skeleton:

  1. Console.php
  2. Console / Greet.php
  3. In the gang class builder connect the console class like this: Builder.php

Attention, replace NamespacePlaceholder with the namespace of your project (by default, Project ) and BundleNamePlaceholder with the name of your bundle (most likely this is the App ).
')
After that, your structure will be the same as in a fresh project.

Using

Run the console to see the list of available commands:

cd your_project_directory/ ./console #  php ./console 

The result will be something like this:

 Available commands: app:greet Greet the user framework:installWebAssets Symlink or copy bundle web files to the projects web folder framework:generateBundle Generate a new bundle help Print command list and usage 

The help command will show more information and a list of available options:

 ./console help framework:installWebAssets framework:installWebAssets [ --copy ] Symlink or copy bundle web files to the projects web folder Options: copy Whether to copy web directories instead of symlinking them 

Standard commands


Adding custom commands

You have already added a simple app in the project : greet . Working with commands is completely analogous to adding HTTP processors using the \ Project \ App \ Console class. Just add the command name to the array returned by the commandNames () method and add the build <command_name> Command method.

In the constructor of the command you can specify a description and a list of parameters and arguments:

 namespace Project\App\Console; class Greet extends \PHPixie\Console\Command\Implementation { public function __construct($config) { //  $config->description('Greet the user'); //   'message' $config->argument('message') ->description("Message to display"); parent::__construct($config); } /** *      . * $argumentData  $optionData    *  HTTP $request->query()  $request->data() */ public function run($argumentData, $optionData) { $message = $argumentData->get('message', "Have fun coding!"); $this->writeLine($message); } } 

Arguments and options

Suppose we want to add the following command:

 sqldump --user=root --skip-missing -f myDatabase users items 

Here myDatabase is the name of the database, followed by a list of tables that we would like to backup. These are the arguments of our team. And user , skip-missing , and f options. Note that the order in which they are given is important for the arguments, but not for the options. Also short options with one letter use one character - instead of two.

In the code, it will look like this:

 $config->option('user') //  ->required() // ,      'help' ->description("User to connect to the database with"); $config->option('skip-missing') ->description("Don't throw an error if the tables are missing") //   . //-   , //    'true'   . ->flag(); $config->option('f') ->flag() ->description("Force database dump"); 

When describing arguments, one should remember that they should be specified in the order in which they should be present in the command. In our case, the idea database argument is before the tables :

 $config->argument('database') ->required() ->description("Which database to dump the tables from"); $config->argument('tables') ->description("Tables to dump") //    //        , //        ->arrayOf(); 

Now when you start the help, we get the following result:

 ./console help app:sqldump app:sqldump --user=VALUE [ -f ] [ --skip-missing ] DATABASE [ TABLES... ] Options: user User to connect to the database with f Force database dump skip-missing Dont throw an error if the tables are missing Arguments: DATABASE Which database to dump the tables from TABLES Tables to dump 

When you run the command, the run () method will be passed options and arguments, from where you can get them in the same way as in the HTTP processor:

 public function run($argumentData, $optionData) { $database = $argumentData->get('database'); //     $user = $optionData->get('user', 'phpixie'); } 

Input and Output

The easiest method of output to the console is just return-text. But if the process should work for a long time and it is necessary to output an intermediate result, then additional methods can be used:

 public function run($argumentData, $optionData) { //   $this->write("Hello "); //      $this->writeLine("World"); //      $str = $this->readLine(); //   CommandException       //     -   (    Bash). throw new \PHPixie\Console\Exception\CommandException("Something bad happened"); } 

Additionally, you can access the CLI context and work with it already:

 public function run($argumentData, $optionData) { $context = $this->cliContext(); $inputStream = $cliContext->inputStream(); $outputStream = $cliContext->outputStream(); $errorStream = $cliContext->errorStream(); $outputStream->write("Hello"); $errorStream->writeLine("Something bad happened"); $context->setExitCode(1); //    

The status code is useful when checking whether the command was successfully executed from the outside, for example from Bash:

 if ./console app:somecommand ; then echo "Command succeeded" else echo "Command failed" fi 

As I wrote from the very beginning, the component can be easily used without the framework:

 class YourCommandRegistry extends \PHPixie\Console\Registry\Provider\Implementation { public function commandNames() { return ['greet']; } public function buildGreetCommand($config) { return new Greet($config); } } $slice = new \PHPixie\Slice(); $cli = new \PHPixie\CLI(); $registry = new YourCommandRegistry(); $console = new \PHPixie\Console($slice, $cli, $registry); $console->runCommand(); 

Thus, you can add console capabilities to any project, all with minimal dependencies and very intuitive.

Source: https://habr.com/ru/post/314314/


All Articles