在 Laravel 的 CLI 模式下,可以通過以下方式讓命令行輸出更加美觀和專業:
1. 使用 Artisan 輸出助手方法
Laravel 提供了多種輸出樣式方法:
public function handle()
{// 基礎樣式$this->info('成功信息 - 綠色'); // 綠色$this->error('錯誤信息 - 紅色'); // 紅色$this->line('普通信息 - 無顏色'); // 默認色$this->comment('注釋信息 - 黃色'); // 黃色$this->question('問題信息 - 藍綠色'); // 藍綠色// 帶背景色$this->line('<bg=green>綠色背景</>');$this->line('<bg=red;fg=white>紅底白字</>');// 自定義樣式$this->line('<fg=magenta;bg=cyan;options=bold,underscore>紫色粗體帶下劃線</>');
}
2. 表格輸出
展示結構化數據:
public function handle()
{$headers = ['ID', 'Name', 'Email'];$data = [[1, 'John Doe', 'john@example.com'],[2, 'Jane Smith', 'jane@example.com'],[3, 'Bob Johnson', 'bob@example.com'],];$this->table($headers, $data);
}
3. 進度條
長時間任務顯示進度:
public function handle()
{$total = 100;$bar = $this->output->createProgressBar($total);for ($i = 0; $i < $total; $i++) {usleep(50000); // 模擬任務$bar->advance();}$bar->finish();$this->newLine(2); // 空兩行$this->info('任務完成!');
}
4. 交互式命令
創建用戶友好的交互:
public function handle()
{// 詢問輸入$name = $this->ask('請輸入您的姓名');// 密碼輸入(隱藏字符)$password = $this->secret('請輸入密碼');// 確認提示if ($this->confirm('確定要執行此操作嗎?')) {// 選擇列表$role = $this->choice('選擇角色', ['Admin', 'Editor', 'Viewer'], 1);$this->info("用戶 $name 將創建為 $role");} else {$this->error('操作已取消');}
}
5. 高級格式化
使用輸出樣式塊:
public function handle()
{// 標題塊$this->output->title('系統初始化');// 章節標題$this->output->section('數據庫遷移');// 任務列表$this->output->writeln('<comment>執行任務:</comment>');$this->output->listing(['創建用戶表','創建訂單表','創建產品表']);// 水平線$this->output->newLine();$this->output->horizontalLine();// 結果輸出$this->output->success('操作成功完成');$this->output->warning('注意:需要重啟服務');$this->output->note('最后更新:2023-06-01');$this->output->caution('敏感操作需授權');
}
6. 完整示例 - 優雅的命令行工具
<?phpnamespace App\Console\Commands;use Illuminate\Console\Command;
use Symfony\Component\Console\Helper\Table;class UserExport extends Command
{protected $signature = 'export:users {--limit=50 : 導出數量}{--format=csv : 導出格式 [csv, json, table]}';protected $description = '導出用戶數據到文件';public function handle(){$this->output->title('用戶數據導出工具');// 驗證選項$format = $this->option('format');if (!in_array($format, ['csv', 'json', 'table'])) {$this->error("不支持的格式: $format");return 1;}$limit = (int)$this->option('limit');$this->info("準備導出 $limit 條用戶數據...");// 模擬數據獲取$users = $this->getUsers($limit);// 進度條$bar = $this->output->createProgressBar(count($users));$bar->start();// 處理數據$results = [];foreach ($users as $user) {$results[] = [$user['id'],$user['name'],$user['email'],$user['created_at']];$bar->advance();}$bar->finish();$this->newLine(2);// 輸出結果switch ($format) {case 'table':$this->table(['ID', 'Name', 'Email', 'Created'], $results);break;case 'json':$this->line(json_encode($results, JSON_PRETTY_PRINT));break;case 'csv':$filename = "users_".date('Ymd_His').'.csv';$this->saveCsv($filename, $results);$this->info("數據已導出到: $filename");break;}$this->output->success('導出操作成功完成');return 0;}private function getUsers($limit){// 模擬數據庫查詢return array_map(function ($i) {return ['id' => $i + 1,'name' => "User $i",'email' => "user$i@example.com",'created_at' => now()->subDays($i)->format('Y-m-d')];}, range(1, $limit));}private function saveCsv($filename, $data){$handle = fopen($filename, 'w');fputcsv($handle, ['ID', 'Name', 'Email', 'Created']);foreach ($data as $row) {fputcsv($handle, $row);}fclose($handle);}
}
7. 使用技巧和最佳實踐
-
顏色方案:
// 標準顏色:black, red, green, yellow, blue, magenta, cyan, white $this->line('<fg=cyan>青色文字</>');// 自定義顏色(支持256色) $this->line('<fg=#ff9900>橙色文字</>');
-
樣式組合:
$this->line('<fg=white;bg=red;options=bold,underscore>白字紅底粗體帶下劃線</>');
-
響應式布局:
// 獲取終端寬度 $width = $this->output->getTerminalWidth(); $this->line(str_repeat('-', $width));
-
多欄布局:
$this->output->writeln(['<info>多行輸出示例:</info>','第一行內容','第二行內容', ]);
-
調試信息:
$this->output->writeln('<debug>調試信息</>');
-
自定義輸出樣式:
$this->output->getFormatter()->setStyle('highlight', new OutputFormatterStyle('red', 'yellow', ['bold'])); $this->line('<highlight>自定義樣式文本</highlight>');
這些技巧可以讓你的 Laravel 命令行工具:
- 提供專業美觀的用戶界面
- 增強用戶體驗和可讀性
- 清晰展示操作進度和結果
- 支持多種輸出格式和交互方式
- 適配不同終端尺寸和顏色支持
使用這些方法,你可以創建出既實用又美觀的 CLI 應用,提升開發體驗和工具的專業性。