[TOC]
# 命令行
## 簡介
```
// 查看所有可用的 Artisan 命令的列表
$ php artisan list
// 查看命的幫助界面 ,顯示可用參數及選項
$ php artisan help migrate
```
### Tinker 命令 (REPL)
```
// 運行 Artisan 命令 tinker 進入 Tinker 環境
$ php artisan tinker
// 使用 vendor:publish 命令發布 Tinker 配置文件
$ php artisan vendor:publish --provider="Laravel\Tinker\TinkerServiceProvider"
```
### 命令白名單
>[success]Tinker 通過采用白名單的方式來確定允許哪些 Artisan 命令可以在 shell 中運行。默認情況下,你可以運行 `clear-compiled` 、`down`、`env`、 `inspire`、`migrate`、 `optimize`、和 `up` 命令。
```
// 在 config/tinker.php 配置文件中的 commands 數組設置
'commands' => [
// App\Console\Commands\ExampleCommand::class,
],
```
### 別名黑名單
// 在 config/tinker.php 配置文件中的 dont_alias 數組設置
'dont_alias' => [
App\User::class,
],
## 編寫命令
### 生成命令
```
$ php artisan make:command SendEmails
```
### 命令結構
```
// signature 和 description 描述命令與作用
<?php
namespace App\Console\Commands;
use App\User;
use App\DripEmailer;
use Illuminate\Console\Command;
class SendEmails extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'email:send {user}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Send drip e-mails to a user';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @param \App\DripEmailer $drip
* @return mixed
*/
public function handle(DripEmailer $drip)
{
$drip->send(User::find($this->argument('user')));
}
}
```
### 閉包命令
```
// routes/console.php
Artisan::command('build {project}', function ($project) {
$this->info("Building {$project}!");
});
// 輸出 Building test!
$ php artisan build test
```
### 類型提示依賴
```
use App\User;
use App\DripEmailer;
Artisan::command('email:send {user}', function (DripEmailer $drip, $user) {
$drip->send(User::find($user));
});
```
### 閉包命令描述
```
// 使用 describe 方法來為閉包命令添加描述
Artisan::command('build {project}', function ($project) {
$this->info("Building {$project}!");
})->describe('Build the project');
```
## 定義輸出期望
```
// 參數
// 命令定義了一個必須的參數: user
protected $signature = 'email:send {user}';
// 可選參數...
email:send {user?}
// 帶有默認值的可選參數...
email:send {user=foo}
// 選項
// 不接收值的選項,如果 --queue 存在,該選項的值為 true, 否則為 false
protected $signature = 'email:send {user} {--queue}';
$ php artisan email:send 1 --queue
// 帶值的選項
protected $signature = 'email:send {user} {--queue=}';
$ php artisan email:send 1 --queue=default
// 選項簡寫
email:send {user} {--Q|queue}
// 參數輸入數組
email:send {user*}
// 設置 user 的值為 ['foo', 'bar']
$ php artisan email:send foo bar
// 選項輸入數組
email:send {user} {--id=*}
$ php artisan email:send --id=1 --id=2
// 輸入說明
protected $signature = 'email:send
{user : The ID of the user}
{--queue= : Whether the job should be queued}';
```
## Command I/O
### 獲取輸入
```
// 如果參數或選項不存在,則返回 null 。
// 用 argument 和 option 方法接收參數和選項值
public function handle()
{
$userId = $this->argument('user');
}
// 獲取所有參數的數組
$arguments = $this->arguments();
// 獲取一個指定的選項值
$queueName = $this->option('queue');
// 獲取所有的選項值
$options = $this->options();
```
### 交互式輸入
```
public function handle()
{
$name = $this->ask('What is your name?');
}
// secret 方法輸入內容是不可見的,用于敏感信息的輸入
$password = $this->secret('What is the password?');
```
### 請求確認
```
// 默認返回 false,如果用戶輸入 y 或者 yes 則返回 true
if ($this->confirm('Do you wish to continue?')) {
//
}
```
### 自動補全
```
// 可以選擇,或者任意回答
$name = $this->anticipate('What is your name?', ['Taylor', 'Dayle']);
```
### 多重選擇
```
// 預設的選擇,可以設置默認值的索引
$name = $this->choice('What is your name?', ['Taylor', 'Dayle'], $defaultIndex);
```
### 編寫輸出
>[success] 可以使用 `line` 、 `info` 、 `comment` 、 `question` 和 `error` 方法來將輸出發送到終端。每個方法都使用適當的 `ANSI` 顏色表明其目的。
```
// 綠色
public function handle()
{
$this->info('Display this on the screen');
}
// 紅色
$this->error('Something went wrong!');
// 無顏色
$this->line('Display this on the screen');
```
### 表格布局
```
$headers = ['Name', 'Email'];
$users = App\User::all(['name', 'email'])->toArray();
$this->table($headers, $users);
```
### 進度條
>[success] 對于耗時任務,提示進度非常有必要。使用 output 對象就可以創建、加載以及停止進度條。首先,定義好任務總步數,然后,在每次任務執行時加載進度條。
```
$users = App\User::all();
$bar = $this->output->createProgressBar(count($users));
$bar->start();
foreach ($users as $user) {
$this->performTask($user);
$bar->advance();
}
$bar->finish();
```
## 注冊命令
>[info] `app/Console/Commands` 目錄下的命令都會被注冊,這是由于控制臺內核的 `commands` 方法調用了 `load`。實際上,可隨意調用 `load` 來掃描其他目錄下的 Artisan 命令,也可以在 `app/Console/Kernel.php` 文件的 `$commands` 屬性中手動注冊命令的類名。Artisan 啟動時,這個屬性列出的命令都將由 [服務容器](/docs/{{version}}/container) 解析并通過 Artisan 進行注冊。
```
protected function commands()
{
$this->load(__DIR__.'/Commands');
$this->load(__DIR__.'/MoreCommands');
}
protected $commands = [
Commands\SendEmails::class
];
```
## 程序調用命令
```
use Illuminate\Support\Facades\Artisan;
Route::get('/foo', function () {
$exitCode = Artisan::call('email:send', [
'user' => 1, '--queue' => 'default'
]);
//
});
// 命令字符串
Artisan::call('email:send 1 --queue=default');
// 隊列化
Route::get('/foo', function () {
Artisan::queue('email:send', [
'user' => 1, '--queue' => 'default'
]);
//
});
// 隊列化派發的連接或任務
Artisan::queue('email:send', [
'user' => 1, '--queue' => 'default'
])->onConnection('redis')->onQueue('commands');
```
### 傳遞數組值
```
// 數組的選項
Route::get('/foo', function () {
$exitCode = Artisan::call('email:send', [
'user' => 1, '--id' => [5, 13]
]);
});
```
### 傳遞布爾值
```
$exitCode = Artisan::call('migrate:refresh', [
'--force' => true,
]);
```
### 命令的互相調用
```
// 在命令內再調用命令
public function handle()
{
$this->call('email:send', [
'user' => 1, '--queue' => 'default'
]);
//
}
// 控制臺不顯示輸出
$this->callSilent('email:send', [
'user' => 1, '--queue' => 'default'
]);
```
- 入門指南
- 安裝
- 部署
- 基礎功能
- 路由
- 中間件
- CSRF 保護
- 控制器
- 請求
- 響應
- 視圖
- URL
- Session
- 表單驗證
- 錯誤
- 日志
- 前端開發
- Blade 模板
- 本地化
- 腳手架
- 編譯資源 Mix
- 安全相關
- 用戶認證
- API 認證
- 綜合話題
- 命令行
- 廣播
- 緩存
- 集合
- 事件
- 文件存儲
- 輔助函數
- 郵件發送
- 消息通知
- 擴展包開發
- 隊列
- 任務調度
- 數據庫
- 快速入門
- 查詢構造器
- 分頁
- 數據庫遷移
- 數據填充
- Redis
- Eloquent ORM
- 快速入門
- 速查表
- Artisan
- Auth
- Blade
- Cache
- Collection
- Composer
- Config
- Container
- Cookie
- DB
- Environment
- Event
- File
- Helper
- Input
- Lang
- Log
- Model
- Pagination
- Queue
- Redirect
- Request
- Response
- Route
- SSH
- Schema
- Security
- Session
- Storage
- String
- URL
- UnitTest
- Validation
- View