Laravel 5.6:如何通过依赖注入替代Redis门面注入Redis缓存?
Hey there, I get you're looking to move away from the Redis facade and use dependency injection instead—let's walk through exactly how to do this, step by step. I'll focus on Laravel since that's the most common framework where you'd encounter the Redis facade, but the core logic applies to other frameworks too if you're using something else.
1. Know the Contracts/Classes to Inject
First, Laravel provides two key interfaces for Redis dependency injection, depending on your needs:
Illuminate\Contracts\Redis\Factory: Use this if you need access to multiple Redis connections (as defined inconfig/database.phpunder theredissection).Illuminate\Contracts\Redis\Connection: Use this if you only need a single, specific Redis connection (defaults to your app's primary Redis connection unless configured otherwise).
2. Injecting in Controllers
Let's start with the most common use case: controllers. Here's how to implement both approaches:
Example with the Factory Interface
This gives you flexibility to switch between connections:
<?php namespace App\Http\Controllers; use Illuminate\Contracts\Redis\Factory; class UserController extends Controller { protected $redis; // Inject the Redis Factory via constructor public function __construct(Factory $redis) { $this->redis = $redis; } public function storeUser() { // Use the default Redis connection $this->redis->connection()->set('user:1:name', 'Jane Smith'); // Or use a named connection from your config (e.g., "cache") $userName = $this->redis->connection('cache')->get('user:1:name'); } }
Example with a Specific Connection
If you only ever need the default Redis connection, inject the Connection interface directly to skip calling connection():
<?php namespace App\Http\Controllers; use Illuminate\Contracts\Redis\Connection; class UserController extends Controller { protected $redis; public function __construct(Connection $redis) { $this->redis = $redis; } public function fetchUser() { // Directly use the default connection $userName = $this->redis->get('user:1:name'); return response()->json(['username' => $userName]); } }
3. Injecting in Custom Classes
The same logic applies to custom services or classes—just type-hint the interface in the constructor, and Laravel's service container will handle the rest:
<?php namespace App\Services; use Illuminate\Contracts\Redis\Connection; class UserCacheService { protected $redis; public function __construct(Connection $redis) { $this->redis = $redis; } public function cacheUser(int $userId, array $userData) { $this->redis->set("user:{$userId}", json_encode($userData)); $this->redis->expire("user:{$userId}", 3600); // Cache for 1 hour } public function getCachedUser(int $userId): ?array { $data = $this->redis->get("user:{$userId}"); return $data ? json_decode($data, true) : null; } }
You can then inject this service into controllers or other classes seamlessly:
public function store(UserCacheService $cacheService) { $cacheService->cacheUser(1, ['name' => 'Jane Smith', 'email' => 'jane@example.com']); }
4. Binding a Specific Connection (Optional)
If you want to always inject a non-default connection (like your "cache" connection) when using the Connection interface, bind it in your AppServiceProvider:
<?php namespace App\Providers; use Illuminate\Contracts\Redis\Connection; use Illuminate\Support\Facades\Redis; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { public function register() { $this->app->bind(Connection::class, function ($app) { return Redis::connection('cache'); }); } }
Now, every time you inject Connection, it'll automatically use your "cache" connection instead of the default.
5. Bonus: Abstract Cache Injection (For Cache-Specific Use Cases)
If you're using Redis specifically as a cache driver (not for raw Redis operations), you can inject the Illuminate\Contracts\Cache\Repository interface instead. This makes your code driver-agnostic—you can switch to Memcached or another cache later without changing your code:
use Illuminate\Contracts\Cache\Repository; public function __construct(Repository $cache) { $this->cache = $cache; } public function fetchUser() { $user = $this->cache->remember('user:1', 3600, function () { return \App\Models\User::find(1); }); }
内容的提问来源于stack exchange,提问作者GTMeteor

