Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Phrase Module Laravel Package

zxf5115/laravel-phrase-module

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require zxf5115/laravel-phrase-module
    

    Publish the config and migrations:

    php artisan vendor:publish --provider="Zxf5115\PhraseModule\PhraseServiceProvider" --tag="config"
    php artisan vendor:publish --provider="Zxf5115\PhraseModule\PhraseServiceProvider" --tag="migrations"
    php artisan migrate
    
  2. First Use Case Define a phrase in config/phrase.php:

    'welcome' => [
        'en' => 'Welcome to our platform',
        'zh' => '欢迎来到我们的平台',
    ],
    

    Retrieve it in a controller:

    use Zxf5115\PhraseModule\Facades\Phrase;
    
    $welcome = Phrase::get('welcome'); // Returns 'Welcome to our platform' (default locale)
    
  3. Key Files to Review

    • config/phrase.php: Centralized phrase definitions.
    • app/Models/Phrase.php: Model for dynamic phrases (if using DB storage).
    • app/Providers/PhraseServiceProvider.php: Service provider for extensions.

Implementation Patterns

Core Workflows

  1. Static Phrases (Config-Based)

    // Define in config/phrase.php
    'errors' => [
        'validation' => [
            'required' => 'This field is required',
            'email' => 'Invalid email format',
        ],
    ];
    
    // Usage
    Phrase::get('errors.validation.required');
    
  2. Dynamic Phrases (Database-Driven)

    // Create via Tinker or API
    Phrase::create(['key' => 'dynamic.greeting', 'en' => 'Hello, {name}!']);
    
    // Usage with interpolation
    Phrase::get('dynamic.greeting', ['name' => 'John']); // 'Hello, John!'
    
  3. Locale Switching

    // Set locale dynamically
    Phrase::setLocale('zh');
    Phrase::get('welcome'); // Returns '欢迎来到我们的平台'
    
    // Or via middleware (e.g., `app/Http/Middleware/SetLocale.php`)
    
  4. Blade Integration

    <h1>{{ phrase('welcome') }}</h1>
    <p>{{ phrase('errors.validation.required') }}</p>
    

    Register the directive in AppServiceProvider:

    Blade::directive('phrase', function ($key) {
        return "<?php echo \\Zxf5115\\PhraseModule\\Facades\\Phrase::get($key); ?>";
    });
    

Integration Tips

  • Validation Messages: Replace Laravel’s default validation messages by extending the FormRequest class:
    public function messages()
    {
        return [
            'email' => Phrase::get('errors.validation.email'),
        ];
    }
    
  • API Responses: Use phrases in JSON responses:
    return response()->json([
        'error' => Phrase::get('errors.generic'),
    ]);
    
  • Testing: Mock phrases in tests:
    Phrase::shouldReceive('get')->with('welcome')->andReturn('Test Welcome');
    

Gotchas and Tips

Pitfalls

  1. Caching Quirks

    • Phrases are cached by default. Clear cache after updates:
      php artisan cache:clear
      
    • Disable caching in config/phrase.php for development:
      'cache_enabled' => env('APP_ENV') !== 'local',
      
  2. Locale Fallback

    • If a translation is missing, the package falls back to the default locale (app/config/app.php). Ensure your config/phrase.php includes all required locales.
  3. Key Collisions

    • Avoid using dots (.) in phrase keys if you later need to access them as nested arrays. Use underscores (_) instead:
      // Good
      'user_profile_name' => 'Profile Name'
      
      // Bad (may cause issues with nested access)
      'user.profile.name' => 'Profile Name'
      
  4. Database Storage Overhead

    • Dynamic phrases stored in the database may bloat your schema. Use config-based phrases for static content.

Debugging

  • Missing Phrases: Check if the key exists in config/phrase.php or the database. Enable debug mode:
    Phrase::enableDebug(); // Logs missing phrases to Laravel logs
    
  • Locale Issues: Verify the app locale in config/app.php matches your expected default.

Extension Points

  1. Custom Storage Override the storage engine by binding a new implementation to the phrase.storage interface:

    $this->app->bind('phrase.storage', function () {
        return new CustomPhraseStorage();
    });
    

    Example interface:

    interface PhraseStorage {
        public function get($key, array $replace = [], $locale = null);
        public function all($locale = null);
    }
    
  2. Event Hooks Listen for phrase events (e.g., PhraseRetrieved) to log or modify phrases:

    event(new PhraseRetrieved($key, $phrase, $locale));
    
  3. Dynamic Phrase Validation Extend the Phrase model to add custom validation rules:

    use Illuminate\Database\Eloquent\Model;
    
    class Phrase extends Model {
        protected $rules = [
            'key' => 'required|unique:phrases|regex:/^[a-z_]+(\.[a-z_]+)*$/i',
        ];
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle