Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Artisan Console完成 #47

Merged
merged 4 commits into from
Oct 3, 2015
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
140 changes: 70 additions & 70 deletions artisan.md
Original file line number Diff line number Diff line change
@@ -1,48 +1,48 @@
# Artisan Console

- [Introduction](#introduction)
- [Writing Commands](#writing-commands)
- [Command Structure](#command-structure)
- [Command I/O](#command-io)
- [Defining Input Expectations](#defining-input-expectations)
- [Retrieving Input](#retrieving-input)
- [Prompting For Input](#prompting-for-input)
- [Writing Output](#writing-output)
- [Registering Commands](#registering-commands)
- [Calling Commands Via Code](#calling-commands-via-code)
# Artisan 控制台

- [介绍](#introduction)
- [编写命令](#writing-commands)
- [命令结构](#command-structure)
- [命令 I/O](#command-io)
- [定义输入期望值](#defining-input-expectations)
- [获取输入值](#retrieving-input)
- [输入提示](#prompting-for-input)
- [编写输出](#writing-output)
- [注册命令](#registering-commands)
- [通过代码调用命令](#calling-commands-via-code)

<a name="introduction"></a>
## Introduction
## 介绍

Artisan is the name of the command-line interface included with Laravel. It provides a number of helpful commands for your use while developing your application. It is driven by the powerful Symfony Console component. To view a list of all available Artisan commands, you may use the `list` command:
Artisan是包含在Laravel中命令行界面的名字。 它提供了很多有用的命令用于开发你的程序。它是基于强大的Symfony控制台组件开发。想要查看所有可用的Artisan命令,你可以使用‘list’命令:

php artisan list

Every command also includes a "help" screen which displays and describes the command's available arguments and options. To view a help screen, simply precede the name of the command with `help`:
每个命令也包含了一个帮助界面去显示和描述该命令可用的参数和选项。要查看帮助界面,可以使用‘help’命令:

php artisan help migrate

<a name="writing-commands"></a>
## Writing Commands
## 编写命令

In addition to the commands provided with Artisan, you may also build your own custom commands for working with your application. You may store your custom commands in the `app/Console/Commands` directory; however, you are free to choose your own storage location as long as your commands can be autoloaded based on your `composer.json` settings.
除了Artisan提供的命令,你也可以创建自定义命令在你的程序中使用。你可以把你的自定义命令保存到`app/Console/Commands`目录中;尽管如此,你也可以选择保存到任意地方只要你的命令能被自动加载基于你的`composer.json`配置。

To create a new command, you may use the `make:console` Artisan command, which will generate a command stub to help you get started:
要编写一个新命令,你可以用这个Artisan命令`make:console`生成一个命令存根来帮助你开始:

php artisan make:console SendEmails

The command above would generate a class at `app/Console/Commands/SendEmails.php`. When creating the command, the `--command` option may be used to assign the terminal command name:
上面这个命令会在`app/Console/Commands/SendEmails.php`上生成一个类。 创建命令的时候,这个`--command`选项可以用来定义终端命令名字:

php artisan make:console SendEmails --command=emails:send

<a name="command-structure"></a>
### Command Structure
### 命令结构

Once your command is generated, you should fill out the `signature` and `description` properties of the class, which will be used when displaying your command on the `list` screen.
你的命令生成之后,你应该填写这个类的`signature``description`属性,这两个属性用来显示你的命令在`list`界面。

The `handle` method will be called when your command is executed. You may place any command logic in this method. Let's take a look at an example command.
当你的命令被执行的时候,`handle`方法会被调用。你可以在这个方法中编写任意命令逻辑。让我们来看一个例子命令。

Note that we are able to inject any dependencies we need into the command's constructor. The Laravel [service container](/docs/{{version}}/container) will automatically inject all dependencies type-hinted in the constructor. For greater code reusability, it is good practice to keep your console commands light and let them defer to application services to accomplish their tasks.
记住这个:我们可以在命令的构造器中注入任何我们需要的依赖。Laravel [service container](/docs/{{version}}/container)会自动注入所有类型提示的依赖在构造器中。为了更好的代码复用性,保持你的命令轻量和让他们顺从程序服务去完成他们的任务是一个好习惯。

<?php

Expand Down Expand Up @@ -101,14 +101,14 @@ Note that we are able to inject any dependencies we need into the command's cons
}

<a name="command-io"></a>
## Command I/O
## 命令 I/O

<a name="defining-input-expectations"></a>
### Defining Input Expectations
### 定义输入期望值

When writing console commands, it is common to gather input from the user through arguments or options. Laravel makes it very convenient to define the input you expect from the user using the `signature` property on your commands. The `signature` property allows you to define the name, arguments, and options for the command in a single, expressive, route-like syntax.
编写命令的时候,一般是通过参数或者选项获取用户的输入。Laravel通过使用你的命令的`signature`属性让定义你期望的用户输入变得很方便。这个`signature`属性允许你通过一种简单的,有表现力的,易读的语法定义命令的名字,参数和选项。

All user supplied arguments and options are wrapped in curly braces, for example:
所有用户输入的参数和选项会被包入大括号中,例如:

/**
* The name and signature of the console command.
Expand All @@ -117,15 +117,15 @@ All user supplied arguments and options are wrapped in curly braces, for example
*/
protected $signature = 'email:send {user}';

In this example, the command defines one **required** argument: `user`. You may also make arguments optional and define default values for optional arguments:
在这个例子中,这个命令定义了一个必填参数:`user`。你也可以把参数设为可选和给可选参数定义默认值:

// Optional argument...
// 可选参数...
email:send {user?}

// Optional argument with default value...
// 可选参数和默认值...
email:send {user=foo}

Options, like arguments, also are a form of user input. However, they are prefixed by two hyphens (`--`) when they are specified on the command line. We can define options in the signature like so:
选项,像参数一样,也是一种用户输入形式。虽然如此,他们在命令行中输入的时候需要加两个短横线(`--`)作为前缀。我们可以这样定义选项在signature中:

/**
* The name and signature of the console command.
Expand All @@ -134,11 +134,11 @@ Options, like arguments, also are a form of user input. However, they are prefix
*/
protected $signature = 'email:send {user} {--queue}';

In this example, the `--queue` switch may be specified when calling the Artisan command. If the `--queue` switch is passed, the value of the option will be `true`. Otherwise, the value will be `false`:
在这个例子中,这个`--queue`选项在调用这个Artisan命令的时候可以被指定。如果传递了`--queue`选项,它的值为`true`。否则,它的值为`false`

php artisan email:send 1 --queue

You may also specify that the option should be assigned a value by the user by suffixing the option name with a `=` sign, indicating that a value should be provided:
你也可以让用户给这个选项赋值通过在选项后加等于号`=`,来指示这个值将会由用户来指定:

/**
* The name and signature of the console command.
Expand All @@ -147,17 +147,17 @@ You may also specify that the option should be assigned a value by the user by s
*/
protected $signature = 'email:send {user} {--queue=}';

In this example, the user may pass a value for the option like so:
这个例子中,用户可以像这样给这个选项赋值:

php artisan email:send 1 --queue=default

You may also assign default values to options:
你也可以给这个选项指定默认值:

email:send {user} {--queue=default}

#### Input Descriptions
#### 输入描述

You may assign descriptions to input arguments and options by separating the parameter from the description using a colon:
你可以为参数和选项定义描述如下通过冒号分割参数与描述:

/**
* The name and signature of the console command.
Expand All @@ -169,11 +169,11 @@ You may assign descriptions to input arguments and options by separating the par
{--queue= : Whether the job should be queued}';

<a name="retrieving-input"></a>
### Retrieving Input
### 获取输入

While your command is executing, you will obviously need to access the values for the arguments and options accepted by your command. To do so, you may use the `argument` and `option` methods:
当你的命令执行的时候,很明显你需要获取你的命令接收的参数及选项的值。想要获取这些值,你可以使用`argument` `option`方法:

To retrieve the value of an argument, use the `argument` method:
获取某个参数的值,使用`argument`方法:

/**
* Execute the console command.
Expand All @@ -187,24 +187,24 @@ To retrieve the value of an argument, use the `argument` method:
//
}

If you need to retrieve all of the arguments as an `array`, call the `argument` with no parameters:
如果你需要获取所有参数的值来作为一个数组,调用无参方法`argument`

$arguments = $this->argument();

Options may be retrieved just as easily as arguments using the `option` method. Like the `argument` method, you may call `option` without any arguments in order to retrieve all of the options as an `array`:
通过`option`方法可以获取选项的值,就像获取参数的值一样简单。和`argument`方法一样,通过调用无参方法`option`可以获取到所有的选项值来作为一个数组:

// Retrieve a specific option...
$queueName = $this->option('queue');

// Retrieve all options...
$options = $this->option();

If the argument or option does not exist, `null` will be returned.
如果参数和选项不存在,将返回空值`null`

<a name="prompting-for-input"></a>
### Prompting For Input
### 输入提示

In addition to displaying output, you may also ask the user to provide input during the execution of your command. The `ask` method will prompt the user with the given question, accept their input, and then return the user's input back to your command:
为了显示输出,在你的命令执行过程中你可能需要向用户请求输入一些信息。这个`ask`方法就可以通过既定的问题提示用户,然后获取用户输入的信息并返回给你的命令:

/**
* Execute the console command.
Expand All @@ -216,34 +216,34 @@ In addition to displaying output, you may also ask the user to provide input dur
$name = $this->ask('What is your name?');
}

The `secret` method is similar to `ask`, but the user's input will not be visible to them as they type in the console. This method is useful for asking for sensitive information such as a password:
这个`secret`方法和`ask`方法类似,但在用户输入时输入信息用户不可见。这个方法会很有用当要求用户输入一些敏感信息的时候,例如密码:

$password = $this->secret('What is the password?');

#### Asking For Confirmation
#### 请求确认

If you need to ask the user for a simple confirmation, you may use the `confirm` method. By default, this method will return `false`. However, if the user enters `y` in response to the prompt, the method will return `true`.
如果你需要请求用户做一个简单确认,你可以使用`confirm`方法。默认这个方法会返回`false`。虽然如此,如果用户输入了`y`作为回应,这个方法会返回`true`

if ($this->confirm('Do you wish to continue? [y|N]')) {
//
}

#### Giving The User A Choice
#### 给用户一个选择

The `anticipate` method can be used to provided autocompletion for possible choices. The user can still choose any answer, regardless of the choices.
`anticipate`方法用来为可能的选择做自动填充。用户仍然可以填任何答案而无视这些选项。

$name = $this->anticipate('What is your name?', ['Taylor', 'Dayle']);

If you need to give the user a predefined set of choices, you may use the `choice` method. The user chooses the index of the answer, but the value of the answer will be returned to you. You may set the default value to be returned if nothing is chosen:
如果你需要让用户必须从给定的选项中选,你可以使用`choice`方法。用户选择答案的索引,但答案的值返回给你。你可以设定返回默认值如果什么都没有选的话:

$name = $this->choice('What is your name?', ['Taylor', 'Dayle'], false);

<a name="writing-output"></a>
### Writing Output
### 编写输出

To send output to the console, use the `info`, `comment`, `question` and `error` methods. Each of these methods will use the appropriate ANSI colors for their purpose.
使用`info`,`comment`,`question``error`方法,可以发送输出到命令行。这些方法中的每一个都会根据他们的目的使用合适的ANSI颜色来显示。

To display an information message to the user, use the `info` method. Typically, this will display in the console as green text:
使用`info`方法来显示信息。一般情况下,在命令行中会显示为绿色文本:

/**
* Execute the console command.
Expand All @@ -255,23 +255,23 @@ To display an information message to the user, use the `info` method. Typically,
$this->info('Display this on the screen');
}

To display an error message, use the `error` method. Error message text is typically displayed in red:
使用`error`方法来显示错误信息。一般情况下,在命令行中会显示为红色文本:

$this->error('Something went wrong!');

#### Table Layouts
#### 表格布局

The `table` method makes it easy to correctly format multiple rows / columns of data. Just pass in the headers and rows to the method. The width and height will be dynamically calculated based on the given data:
`table`方法让以正确格式显示多行多列数据变得很容易。只需要把表头和记录传给这个方法。宽和高都会被动态计算出来根据传入的数据:

$headers = ['Name', 'Email'];

$users = App\User::all(['name', 'email'])->toArray();

$this->table($headers, $users);

#### Progress Bars
#### 进度条

For long running tasks, it could be helpful to show a progress indicator. Using the output object, we can start, advance and stop the Progress Bar. You have to define the number of steps when you start the progress, then advance the Progress Bar after each step:
对于耗时任务,显示一个进度条是很有帮助的。使用输出对象,我们可以开始,推进和停止进度。你必须定义总步数当开始进度的时候,然后在每一步完成之后推进进度:

$users = App\User::all();

Expand All @@ -285,23 +285,23 @@ For long running tasks, it could be helpful to show a progress indicator. Using

$this->output->progressFinish();

For more advanced options, check out the [Symfony Progress Bar component documentation](http:https://symfony.com/doc/2.7/components/console/helpers/progressbar.html).
想了解更多高级选项,请查看 [Symfony Progress Bar component documentation](http:https://symfony.com/doc/2.7/components/console/helpers/progressbar.html).

<a name="registering-commands"></a>
## Registering Commands
## 注册命令

Once your command is finished, you need to register it with Artisan so it will be available for use. This is done within the `app/Console/Kernel.php` file.
当你的命令完成之后,你需要注册才可以使用。这个可以在`app/Console/Kernel.php`文件中完成。

Within this file, you will find a list of commands in the `commands` property. To register your command, simply add the class name to the list. When Artisan boots, all the commands listed in this property will be resolved by the [service container](/docs/{{version}}/container) and registered with Artisan:
在这个文件中,你会发现一个命令列表在`commands`属性中。要注册你的命令,只需要简单的把类名加到列表中。当Artisan启动时,所有在这个属性中的命令都会被[service container](/docs/{{version}}/container)解析和用Artisan注册:

protected $commands = [
'App\Console\Commands\SendEmails'
];

<a name="calling-commands-via-code"></a>
## Calling Commands Via Code
## 通过代码调用命令

Sometimes you may wish to execute an Artisan command outside of the CLI. For example, you may wish to fire an Artisan command from a route or controller. You may use the `call` method on the `Artisan` facade to accomplish this. The `call` method accepts the name of the command as the first argument, and an array of command parameters as the second argument. The exit code will be returned:
有时候你可能希望执行一个Artisan命令在命令行之外。例如,你希望触发一个Artisan命令在一个路由或者控制器里。你可以通过`Artisan` facade的`call`方法去完成它。`call`方法接收命令名作为第一个参数,命令参数数组作为第二个参数。退出代码(exit code)将被返回:

Route::get('/foo', function () {
$exitCode = Artisan::call('email:send', [
Expand All @@ -311,7 +311,7 @@ Sometimes you may wish to execute an Artisan command outside of the CLI. For exa
//
});

Using the `queue` method on the `Artisan` facade, you may even queue Artisan commands so they are processed in the background by your [queue workers](/docs/{{version}}/queues):
使用`Artisan` facade的`queue`方法,你甚至可以把命令放入队列,这样他们就可以在后台通过[queue workers](/docs/{{version}}/queues)被处理:

Route::get('/foo', function () {
Artisan::queue('email:send', [
Expand All @@ -321,15 +321,15 @@ Using the `queue` method on the `Artisan` facade, you may even queue Artisan com
//
});

If you need to specify the value of an option that does not accept string values, such as the `--force` flag on the `migrate:refresh` command, you may pass a boolean `true` or `false`:
如果你需要指定的选项不接收字符串,例如`migrate:refresh`命令的`--force`选项,你可以传递一个布尔值`true` 或者 `false`

$exitCode = Artisan::call('migrate:refresh', [
'--force' => true,
]);

### Calling Commands From Other Commands
### 从其他命令中调用命令

Sometimes you may wish to call other commands from an existing Artisan command. You may do so using the `call` method. This `call` method accepts the command name and an array of command parameters:
有时你希望从已有Artisan命令中调用其它命令。你可以使用`call`方法。这个`call`方法接收命令名和命令参数数组作为参数:

/**
* Execute the console command.
Expand All @@ -345,7 +345,7 @@ Sometimes you may wish to call other commands from an existing Artisan command.
//
}

If you would like to call another console command and suppress all of its output, you may use the `callSilent` method. The `callSilent` method has the same signature as the `call` method:
如果你想调用另一个命令并忽略它所有的输出,你可以使用`callSilent`方法。`callSilent`方法接收的参数和`call`方法一样:

$this->callSilent('email:send', [
'user' => 1, '--queue' => 'default'
Expand Down