Weave 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

Globals Provider Laravel Package

boson-php/globals-provider

Laravel package that exposes PHP superglobals and environment values through a service provider, offering a consistent way to access and share request/runtime globals across your app, with simple configuration and container bindings for easier testing.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require boson-php/globals-provider
    

    Register the service provider in config/app.php:

    'providers' => [
        // ...
        Boson\GlobalsProvider\GlobalsServiceProvider::class,
    ],
    
  2. First Use Case Access global values via the Globals facade:

    use Boson\GlobalsProvider\Facades\Globals;
    
    // Set a global value
    Globals::set('app_name', 'MyApp');
    
    // Retrieve a global value
    $appName = Globals::get('app_name'); // Returns 'MyApp'
    
  3. Configuration Publish the config file (if needed):

    php artisan vendor:publish --provider="Boson\GlobalsProvider\GlobalsServiceProvider" --tag="config"
    

    Default config is minimal; override in config/globals.php:

    return [
        'prefix' => 'globals_', // Optional prefix for keys
        'cache' => [
            'enabled' => true,
            'driver' => 'file', // Supports 'file', 'redis', 'array'
        ],
    ];
    

Implementation Patterns

Core Workflows

  1. Centralized Configuration Use globals for app-wide settings (e.g., feature flags, API endpoints):

    // config/app.php
    Globals::set('api.base_url', env('API_BASE_URL', 'https://api.example.com'));
    
    // In a controller
    $url = Globals::get('api.base_url');
    
  2. Dynamic Feature Toggles Toggle features without redeploying:

    if (Globals::get('features.new_ui', false)) {
        return view('new-ui');
    }
    
  3. Environment-Specific Overrides Load environment-specific globals via service provider boot:

    public function boot()
    {
        if (app()->environment('local')) {
            Globals::set('debug.toolbar', true);
        }
    }
    

Integration Tips

  • Cache Integration Enable caching in config/globals.php for performance:

    'cache' => [
        'enabled' => true,
        'driver' => env('GLOBALS_CACHE_DRIVER', 'file'),
    ],
    

    Clear cache manually or via events (e.g., Globals::clear()).

  • Middleware for Contextual Globals Set request-scoped globals in middleware:

    public function handle($request, Closure $next)
    {
        Globals::set('user.id', auth()->id());
        return $next($request);
    }
    
  • Validation Layer Add a trait to validate globals on retrieval:

    trait ValidatesGlobals {
        protected function getValidatedGlobal($key, $default = null, $validator = null)
        {
            $value = Globals::get($key, $default);
            return $validator ? $validator($value) : $value;
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Key Collisions

    • Without a prefix (e.g., globals_), keys may conflict with Laravel’s built-in storage (e.g., session, cache).
    • Fix: Always use a prefix in config/globals.php:
      'prefix' => 'app_globals_',
      
  2. Cache Invalidation

    • Cached globals won’t update until Globals::clear() is called.
    • Tip: Bind a cache tag to globals and clear it via events or commands:
      Globals::clear('app_globals_*'); // Clear all prefixed globals
      
  3. Thread Safety

    • Globals are not thread-safe. Avoid setting globals in queued jobs or parallel processes without synchronization.
  4. Serialization Issues

    • Complex objects (e.g., Closures, Resources) cannot be stored. Use strings/arrays or serialize simple objects:
      Globals::set('user_data', json_encode($user));
      $data = json_decode(Globals::get('user_data'));
      

Debugging

  • Inspect All Globals Use Tinker to dump all globals:

    php artisan tinker
    >>> \Boson\GlobalsProvider\Facades\Globals::all();
    
  • Check Cache Driver If globals aren’t updating, verify the cache driver is configured correctly in .env:

    GLOBALS_CACHE_DRIVER=redis
    CACHE_DRIVER=redis
    

Extension Points

  1. Custom Storage Backends Extend the GlobalsManager to support databases or external APIs:

    // app/Providers/GlobalsServiceProvider.php
    public function register()
    {
        $this->app->singleton('globals', function ($app) {
            return new \Boson\GlobalsProvider\GlobalsManager(
                new \App\Services\CustomGlobalsStore()
            );
        });
    }
    
  2. Event Hooks Listen for global changes via events (if the package emits them). Example:

    // app/Providers/EventServiceProvider.php
    protected $listen = [
        'Boson\GlobalsProvider\Events\GlobalSet' => [
            \App\Listeners\LogGlobalChange::class,
        ],
    ];
    
  3. Laravel Scout Integration Index globals for search:

    Globals::search('feature_*')->get(); // Hypothetical; requires custom implementation.
    
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.
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel
draftsmaninc/draftsman
square-bit/laravel-volition
himito/laravel-mailman
htinlynn/genius-helper
maco-studios/hephaestus
elmogy/larafast
xeviant/laravel-paystack
gorilladash/laravel-website-sdk
martialbe/flysystem-oss
chondal/3312client
jeroen-g/flickr
opscale-co/nova-genbi
itsjustvita/laravel-retention
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log