laravel在cli模式下输出格式漂亮一些

在 Laravel 的 CLI 模式下,可以通过以下方式让命令行输出更加美观和专业:

1. 使用 Artisan 输出助手方法

Laravel 提供了多种输出样式方法:

php 复制代码
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. 表格输出

展示结构化数据:

php 复制代码
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. 进度条

长时间任务显示进度:

php 复制代码
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. 交互式命令

创建用户友好的交互:

php 复制代码
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. 高级格式化

使用输出样式块:

php 复制代码
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. 完整示例 - 优雅的命令行工具

php 复制代码
<?php

namespace 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. 使用技巧和最佳实践

  1. 颜色方案

    php 复制代码
    // 标准颜色:black, red, green, yellow, blue, magenta, cyan, white
    $this->line('<fg=cyan>青色文字</>');
    
    // 自定义颜色(支持256色)
    $this->line('<fg=#ff9900>橙色文字</>');
  2. 样式组合

    php 复制代码
    $this->line('<fg=white;bg=red;options=bold,underscore>白字红底粗体带下划线</>');
  3. 响应式布局

    php 复制代码
    // 获取终端宽度
    $width = $this->output->getTerminalWidth();
    $this->line(str_repeat('-', $width));
  4. 多栏布局

    php 复制代码
    $this->output->writeln([
        '<info>多行输出示例:</info>',
        '第一行内容',
        '第二行内容',
    ]);
  5. 调试信息

    php 复制代码
    $this->output->writeln('<debug>调试信息</>');
  6. 自定义输出样式

    php 复制代码
    $this->output->getFormatter()->setStyle('highlight', new OutputFormatterStyle('red', 'yellow', ['bold']));
    $this->line('<highlight>自定义样式文本</highlight>');

这些技巧可以让你的 Laravel 命令行工具:

  • 提供专业美观的用户界面
  • 增强用户体验和可读性
  • 清晰展示操作进度和结果
  • 支持多种输出格式和交互方式
  • 适配不同终端尺寸和颜色支持

使用这些方法,你可以创建出既实用又美观的 CLI 应用,提升开发体验和工具的专业性。

相关推荐
fakaifa2 小时前
【同步更新】最新版龙兵名片装修版系统+小程序前端+搭建教程
前端·小程序·php·源码下载·龙兵名片·龙兵名片装饰
onejason5 小时前
《PHP 爬虫实战指南:获取淘宝店铺详情》
前端·后端·php
用户3074596982077 小时前
PHP 抽象类完全指南(含 PHP 8.4 新特性)
php
嵌入式×边缘AI:打怪升级日志8 小时前
韦东山STM32_HAl库入门教程(SPI)学习笔记[09]内容
stm32·嵌入式硬件·microsoft
CodeCraft Studio8 小时前
图像处理控件Aspose.Imaging教程:使用 C# 将 SVG 转换为 EMF
图像处理·microsoft·c#·svg·aspose·图片格式转换·emf
用户3074596982079 小时前
📘 PHP 继承与静态机制深度解析
php
卑微的小鬼9 小时前
TCP如何实现可靠传输?实现细节?
网络·tcp/ip·php
初九之潜龙勿用13 小时前
技术与情感交织的一生 (十一)
服务器·笔记·microsoft·印象笔记
wuzuyu36513 小时前
Laravel The requested URL /hellowzy was not found on this server. 404 问题的解决
php·laravel