You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 5.6多语言文件生成工具:支持多级命名空间扫描

解决方案:Laravel 5.6 扫描翻译键并生成多级命名空间语言文件

针对你在Laravel 5.6多语言项目里遇到的需求——扫描@lang指令和trans()函数里的翻译键,还得支持namespace/another-namespace.translation-string这种多级命名空间并自动生成嵌套目录的语言文件,我整理了两个实用方案,亲测适配你的场景:

方案一:自定义Artisan命令(最灵活,适配旧版本)

因为Laravel 5.6属于比较早的版本,很多新包可能兼容性不佳,自己写个命令反而更靠谱。步骤如下:

  1. 生成命令文件
    在终端执行:

    php artisan make:command ScanTranslationKeys
    
  2. 编写扫描与生成逻辑
    打开app/Console/Commands/ScanTranslationKeys.php,替换成以下代码:

    <?php
    
    namespace App\Console\Commands;
    
    use Illuminate\Console\Command;
    use Illuminate\Support\Facades\File;
    use Illuminate\Support\Str;
    
    class ScanTranslationKeys extends Command
    {
        protected $signature = 'trans:scan {locale=en}';
        protected $description = 'Scan all translation keys in Blade/PHP files and generate nested namespace language files';
    
        public function handle()
        {
            $locale = $this->argument('locale');
            $langBasePath = resource_path("lang/{$locale}");
    
            // 定义要扫描的目录(可根据项目调整)
            $scanPaths = [
                resource_path('views'),
                app_path(),
                // 可以添加更多目录,比如routes/
            ];
    
            $collectedKeys = [];
    
            foreach ($scanPaths as $path) {
                // 跳过vendor目录,避免扫描第三方代码
                if (str_contains($path, 'vendor')) continue;
    
                $files = File::allFiles($path);
                foreach ($files as $file) {
                    $content = File::get($file);
                    // 匹配trans()函数中的翻译键
                    preg_match_all('/trans\([\'"](.*?)[\'"]\)/', $content, $transMatches);
                    // 匹配@Blade指令中的翻译键
                    preg_match_all('/@lang\([\'"](.*?)[\'"]\)/', $content, $langMatches);
    
                    // 合并两类匹配到的键
                    $keys = array_merge($transMatches[1], $langMatches[1]);
                    foreach ($keys as $key) {
                        $this->parseAndCollectKey($key, $collectedKeys);
                    }
                }
            }
    
            // 生成/更新语言文件
            foreach ($collectedKeys as $namespace => $keyTree) {
                $filePath = $langBasePath . '/' . str_replace('/', '/', $namespace) . '.php';
                // 自动创建嵌套目录
                File::ensureDirectoryExists(dirname($filePath));
    
                // 合并现有文件内容,避免覆盖已有的翻译
                $existingTranslations = File::exists($filePath) ? require $filePath : [];
                $finalTranslations = array_merge_recursive($existingTranslations, $keyTree);
    
                // 写入文件(用var_export保持数组格式可读性)
                File::put($filePath, '<?php return ' . var_export($finalTranslations, true) . ';');
                $this->info("Updated: {$filePath}");
            }
    
            $this->info('✅ Translation key scanning and file generation finished!');
        }
    
        /**
         * 解析翻译键,拆分多级命名空间和嵌套键
         */
        protected function parseAndCollectKey(string $key, array &$collectedKeys)
        {
            // 按第一个.拆分命名空间和翻译键部分
            $keyParts = explode('.', $key, 2);
            if (count($keyParts) !== 2) {
                $this->warn("Skipping invalid key: {$key}");
                return;
            }
    
            [$namespace, $translationPath] = $keyParts;
            // 把命名空间中的/转成目录分隔符
            $namespacePath = str_replace('/', '/', $namespace);
            // 拆分翻译键为嵌套数组路径
            $translationKeys = explode('.', $translationPath);
    
            $currentNode = &$collectedKeys[$namespacePath];
            foreach ($translationKeys as $part) {
                if (!isset($currentNode[$part])) {
                    $currentNode[$part] = [];
                }
                $currentNode = &$currentNode[$part];
            }
    
            // 设置默认翻译(这里用键的友好形式,可自定义)
            if (empty($currentNode)) {
                $currentNode = Str::title(str_replace('_', ' ', end($translationKeys)));
            }
        }
    }
    
  3. 使用命令

    • 生成英文语言文件:
      php artisan trans:scan
      
    • 生成其他语言(比如西班牙语):
      php artisan trans:scan es
      

    举个例子,如果你有trans('admin/user.profile.full_name'),命令会自动创建resources/lang/en/admin/user.php,文件内容如下:

    <?php return array (
      'profile' => 
      array (
        'full_name' => 'Full Name',
      ),
    );
    

方案二:适配旧版本的第三方包

如果你不想自己写代码,可以试试barryvdh/laravel-translation-manager的2.x版本(适配Laravel 5.x),但默认它不支持/分隔的多级命名空间,需要做小修改:

  1. 安装包

    composer require barryvdh/laravel-translation-manager:2.5.*
    
  2. 修改扫描逻辑
    找到包的扫描类(通常在vendor/barryvdh/laravel-translation-manager/src/Manager.php),修改其中处理翻译键的方法,把命名空间中的/替换成目录分隔符,这样生成文件时会自动创建嵌套目录。

    核心思路是在拆分键的时候,将namespace/another识别为嵌套目录,而不是单个命名空间。

注意事项

  • 扫描前建议备份现有resources/lang目录,避免意外覆盖重要翻译内容;
  • 可以根据项目需求调整scanPaths数组,添加或移除需要扫描的目录;
  • 自定义命令中的默认翻译规则可以根据你的需求修改(比如留空或者用其他格式)。

内容的提问来源于stack exchange,提问作者jacobdo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 09:04:32