laravel在cli模式下输出格式漂亮一些
在 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 应用,提升开发体验和工具的专业性。