tutorial-console.md 7.97 KB
Newer Older
1 2
Console applications
====================
3

4
> Note: This section is under development.
Qiang Xue committed
5

Larry Ullman committed
6 7
Yii has full featured support for console applications, whose structure is very similar to a Yii web application. A console application
consists of one or more [[yii\console\Controller]] classes, which are often referred to as "commands" in the console environment. Each controller can also have one or more actions, just like web controllers.
8

9

Valentin Ts committed
10
Usage <a name="usage"></a>
11 12
-----

Larry Ullman committed
13
You execute a console controller action using the following syntax:
14 15

```
16
yii <route> [--option1=value1 --option2=value2 ... argument1 argument2 ...]
17 18
```

Larry Ullman committed
19
For example, the [[yii\console\controllers\MigrateController::actionCreate()|MigrateController::actionCreate()]]
20
with [[yii\console\controllers\MigrateController::$migrationTable|MigrateController::$migrationTable]] set can
Larry Ullman committed
21
be called from command line like so:
22 23

```
kate-kate committed
24
yii migrate/create --migrationTable=my_migration
25 26
```

27 28 29 30 31
In the above `yii` is the console application entry script which is described below.

> **Note**: When using `*` in console don't forget to quote it as `"*"` in order to avoid executing it as a shell
> glob that will be replaced by all file names of the current directory.

32

Valentin Ts committed
33
Entry script <a name="entry-script"></a>
34 35
------------

36 37 38
The console application entry script is equivalent to the `index.php` bootstrap file used for the web application.
The console entry script is typically called `yii`, and located in your application's root directory.
It contains code like the following:
39 40 41 42 43 44 45 46

```php
#!/usr/bin/env php
<?php
/**
 * Yii console bootstrap file.
 */

47
defined('YII_DEBUG') or define('YII_DEBUG', true);
48

49
// fcgi doesn't have STDIN and STDOUT defined by default
50 51
defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
defined('STDOUT') or define('STDOUT', fopen('php://stdout', 'w'));
52 53

require(__DIR__ . '/vendor/autoload.php');
Qiang Xue committed
54
require(__DIR__ . '/vendor/yiisoft/yii2/Yii.php');
55 56 57 58 59 60 61 62

$config = require(__DIR__ . '/config/console.php');

$application = new yii\console\Application($config);
$exitCode = $application->run();
exit($exitCode);
```

Larry Ullman committed
63 64
This script will be created as part of your application; you're free to edit it to suit your needs. The `YII_DEBUG` constant can be set `false` if you do
not want to see a stack trace on error, and/or if you want to improve the overall performance. In both basic and advanced application
65 66
templates, the console application entry script has debugging enabled by default to provide a more developer-friendly environment.

67

Valentin Ts committed
68
Configuration <a name="configuration"></a>
69 70
-------------

Larry Ullman committed
71
As can be seen in the code above, the console application uses its own configuration file, named `console.php`. In this file
72
you should configure various [application components](structure-application-components.md) and properties for the console application in particular.
73

Larry Ullman committed
74 75
If your web application and the console application share a lot of configuration parameters and values, you may consider moving the common
parts into a separate file, and including this file in both of the application configurations (web and console). You can see an example of this in the "advanced" application template.
76

77 78 79 80 81 82 83 84 85
> Tipp: Sometimes, you may want to run a console command using an application configuration that is different
> from the one specified in the entry script. For example, you may want to use the `yii migrate` command to
> upgrade your test databases, which are configured in each individual test suite. To do change the configuration
> dynamically, simply specify a custom application configuration
> file via the `appconfig` option when executing the command:
> 
> ```
> yii <route> --appconfig=path/to/config.php ...
> ```
86

87

Valentin Ts committed
88
Creating your own console commands <a name="create-command"></a>
89 90
----------------------------------

91
### Console Controller and Action
92

93
A console command is defined as a controller class extending from [[yii\console\Controller]]. In the controller class,
Larry Ullman committed
94
you define one or more actions that correspond to sub-commands of the controller. Within each action, you write code that implements the appropriate tasks for that particular sub-command.
95

Larry Ullman committed
96 97
When running a command, you need to specify the route to the  controller action. For example,
the route `migrate/create` invokes the sub-command that corresponds to the
98
[[yii\console\controllers\MigrateController::actionCreate()|MigrateController::actionCreate()]] action method.
Larry Ullman committed
99
If a route offered during execution does not contain an action ID, the default action will be executed (as with a web controller).
100

101 102
### Options

103
By overriding the [[yii\console\Controller::options()]] method, you can specify options that are available
Larry Ullman committed
104
to a console command (controller/actionID). The method should return a list of the controller class's public properties.
105 106 107
When running a command, you may specify the value of an option using the syntax `--OptionName=OptionValue`.
This will assign `OptionValue` to the `OptionName` property of the controller class.

Larry Ullman committed
108 109
If the default value of an option is of an array type and you set this option while running the command,
the option value will be converted into an array by splitting the input string on any commas.
110

111 112 113 114
### Arguments

Besides options, a command can also receive arguments. The arguments will be passed as the parameters to the action
method corresponding to the requested sub-command. The first argument corresponds to the first parameter, the second
Larry Ullman committed
115 116
corresponds to the second, and so on. If not enough arguments are provided when the command is called, the corresponding parameters
will take the declared default values, if defined. If no default value is set, and no value is provided at runtime, the command will exit with an error.
117

Larry Ullman committed
118 119
You may use the `array` type hint to indicate that an argument should be treated as an array. The array will be generated
by splitting the input string on commas.
120 121 122 123 124 125

The follow examples show how to declare arguments:

```php
class ExampleController extends \yii\console\Controller
{
126 127
    // The command "yii example/create test" will call "actionCreate('test')"
    public function actionCreate($name) { ... }
128

129 130 131
    // The command "yii example/index city" will call "actionIndex('city', 'name')"
    // The command "yii example/index city id" will call "actionIndex('city', 'id')"
    public function actionIndex($category, $order = 'name') { ... }
132

133 134 135
    // The command "yii example/add test" will call "actionAdd(['test'])"
    // The command "yii example/add test1,test2" will call "actionAdd(['test1', 'test2'])"
    public function actionAdd(array $name) { ... }
136 137 138 139 140
}
```


### Exit Code
141

Larry Ullman committed
142 143 144 145
Using exit codes is a best practice for console application development. Conventionally, a command returns `0` to indicate that
everything is OK. If the command returns a number greater than zero, that's considered to be indicative of an error. The number returned will be the error
code, potentially usable to find out details about the error.
For example `1` could stand generally for an unknown error and all codes above would be reserved for specific cases: input errors, missing files, and so forth.
Carsten Brandt committed
146

Larry Ullman committed
147
To have your console command return an exit code, simply return an integer in the controller action
Carsten Brandt committed
148 149 150 151 152
method:

```php
public function actionIndex()
{
153 154 155 156 157 158
    if (/* some problem */) {
        echo "A problem occured!\n";
        return 1;
    }
    // do something
    return 0;
Carsten Brandt committed
159 160
}
```
161

162
There are some predefined constants you can use:
163

164 165
- `Controller::EXIT_CODE_NORMAL` with value of `0`;
- `Controller::EXIT_CODE_ERROR` with value of `1`.
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185

It's a good practice to define meaningful constants for your controller in case you have more error code types.

### Formatting and colors

Yii console supports formatted output that is automatically degraded to non-formatted one if it's not supported
by terminal running the command.

Outputting formatted strings is simple. Here's how to output some bold text:

```php
$this->stdout("Hello?\n", Console::BOLD);
```

If you need to build string dynamically combining multiple styles it's better to use `ansiFormat`:

```php
$name = $this->ansiFormat('Alex', Console::FG_YELLOW);
echo "Hello, my name is $name.";
```