← Back to Modules

Interactive Demo

Click to see both approaches in action and understand when to use each

🎯 Interactive Demo

Facades vs Dependency Injection

Both approaches work perfectly - the choice depends on your context and preferences. See them in action:

Using Facade (Static-like syntax)

Cache::put('key', 'value', 60);
$value = Cache::get('key');

// Clean, simple, no injection needed
// Perfect for controllers and quick tasks

Cache::put('demo_time', now(), 60)

Using Dependency Injection (Constructor)

public function __construct(
    private CacheManager $cache
) {}

public function demo() {
    $this->cache->put('key', 'value', 60);
    return $this->cache->get('key');
}

// More explicit, better for complex services
// Required for package development

Constructor injection makes dependencies obvious

🎯 Live Example - Both Approaches Work!

This page used the Cache facade to store and retrieve data:

Value Retrieved: Stored via Facade

Code used: Cache::put() and Cache::get()

Facades

✅ Pros:
  • Clean syntax
  • No constructor bloat
  • Familiar to Laravel devs
❌ Cons:
  • Hidden dependencies
  • "Magic" behavior
  • Less obvious

Dependency Injection

✅ Pros:
  • Explicit dependencies
  • Better for testing
  • Package-friendly
❌ Cons:
  • More verbose
  • Constructor can get large
  • More boilerplate

🎓 When to Use Which?

Use Facades when:

  • Working with Laravel's built-in services (Cache, DB, Mail, etc.)
  • In controllers and simple use cases
  • You want clean, concise code

Use Dependency Injection when:

  • Building reusable packages
  • Working with your own business services
  • You want explicit, testable dependencies

💡 Reality Check

In real Laravel apps, developers use both approaches! Facades for framework services in controllers, Dependency Injection for business logic and package development. There's no "wrong" choice - pick what fits your context.