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 Smart Facades Laravel Package

imanghafoori/laravel-smart-facades

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require imanghafoori/laravel-smart-facades
    

    Publish the config (optional):

    php artisan vendor:publish --provider="Imanghafoori\SmartFacades\SmartFacadesServiceProvider"
    
  2. First Use Case: Replace a standard facade call (e.g., Cache::get('key')) with a context-aware approach:

    // Standard facade
    Cache::get('key');
    
    // Smart Facade (context-aware)
    Cache::context('user')->get('key'); // Resolves to a specific cache driver/key based on context
    
  3. Key Files:

    • config/smart-facades.php (for configuration)
    • app/Providers/SmartFacadesServiceProvider.php (for custom strategies)

Implementation Patterns

Core Workflows

  1. Context-Based Resolution: Use contexts to dynamically resolve facade behavior (e.g., cache drivers, database connections, queues).

    // Resolve to 'redis' driver for 'user' context
    Cache::context('user')->get('preferences');
    
    // Fallback to default if no context strategy exists
    Cache::context('unknown')->get('key'); // Uses default driver
    
  2. Strategy Pattern Integration: Define custom strategies for facades (e.g., Cache, DB, Queue).

    // In SmartFacadesServiceProvider.php
    public function register()
    {
        $this->app->singleton('cache.context.user', function ($app) {
            return Cache::extend('redis');
        });
    }
    
  3. Chaining and Method Overrides: Extend facade methods with context-aware logic:

    // Override 'get' for 'user' context
    Cache::context('user')->get('key', function () {
        return 'default_value';
    });
    
  4. Dynamic Facade Aliases: Use aliases for context-specific facades:

    // In config/smart-facades.php
    'aliases' => [
        'UserCache' => 'cache.context.user',
    ];
    
    // Usage
    UserCache::get('key'); // Resolves to 'cache.context.user'
    
  5. Middleware for Facades: Apply middleware to facade calls (e.g., logging, rate-limiting):

    Cache::context('user')->middleware([LogCacheAccess::class])->get('key');
    

Integration Tips

  1. Leverage Existing Facades: Works seamlessly with Laravel’s built-in facades (Cache, DB, Queue, Auth, etc.). Example:

    DB::context('tenant')->table('users')->get();
    
  2. Custom Facade Extension: Extend third-party facades (e.g., Spatie\Permission):

    // In SmartFacadesServiceProvider.php
    $this->app->singleton('permission.context.admin', function ($app) {
        return new PermissionService($app['permission'], 'admin');
    });
    
  3. Testing: Mock context-specific facades in tests:

    $this->app->instance('cache.context.user', Mockery::mock('overload:Cache'));
    
  4. Performance: Cache context resolutions if strategies are static:

    Cache::context('user')->remember('key', 60, function () {
        return Cache::context('user')->get('expensive_key');
    });
    

Gotchas and Tips

Pitfalls

  1. Context Resolution Order:

    • Contexts are resolved left-to-right in chained calls.
    • Example: Cache::context('a')->context('b')->get('key') resolves b first.
    • Fix: Use explicit strategies or flatten contexts.
  2. Circular Dependencies: Avoid recursive context resolutions (e.g., Cache::context('user')->get('cache.context.user')). Fix: Use dependency injection or static strategies.

  3. Middleware Stack Bloat: Overusing middleware can degrade performance. Fix: Limit middleware to critical paths or use decorators.

  4. Facade Overrides: Overriding core facade methods (e.g., Cache::get) may conflict with Laravel’s internal calls. Fix: Prefix custom methods (e.g., Cache::contextGet('key')).

  5. Configuration Cache: After publishing config, clear Laravel’s config cache:

    php artisan config:clear
    

Debugging Tips

  1. Log Context Resolutions: Enable debug mode in config/smart-facades.php:

    'debug' => env('APP_DEBUG', false),
    

    Logs context resolution steps to storage/logs/laravel.log.

  2. Inspect Strategies: Dump registered strategies:

    dd(app()->make('cache.context.user'));
    
  3. Fallback Behavior: Ensure default facades are configured in config/smart-facades.php:

    'defaults' => [
        'cache' => 'file',
        'db' => 'mysql',
    ],
    

Extension Points

  1. Custom Context Providers: Dynamically generate contexts from request data:

    // In SmartFacadesServiceProvider.php
    $this->app->singleton('cache.context.dynamic', function ($app) {
        return Cache::extend(request('tenant') ?? 'default');
    });
    
  2. Facade Events: Dispatch events for context changes:

    Cache::context('user')->get('key'); // Triggers `CacheContextChanged` event
    
  3. API Integration: Use contexts for API versioning or tenant isolation:

    DB::context('api.v2')->table('users')->get();
    
  4. CLI Contexts: Set contexts via artisan commands:

    // In a command
    $this->app->singleton('cache.context.cli', function () {
        return Cache::extend('array');
    });
    
  5. Testing Utilities: Add helper methods to phpunit.xml or TestCase:

    // In TestCase.php
    protected function withContext($context)
    {
        $this->app->instance("cache.context.$context", Cache::extend('array'));
    }
    
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle