Redis on Laravel: Why naming is a pain
It's Thursday night, and you're looking to start using Redis in your Laravel application. You fire up your Homestead box (more on this in another post), open your favourite IDE and put in a new route to start playing around. Just something simple to start, write then read a value, just like the example.
You save, and load up the route in your browser, only to see:
Call to undefined method Redis::connection()
That can't be right, can it? The Redis class is built-in to Laravel, and connection() was in the example. How can it be missing?
As it turns out, Redis is a popular name for Redis classes, so there may be a conflict between Laravel's Redis alias and another Redis class. In my case (and most likely), the Redis PHP extension provided by the php-redis package. Are you sick of me saying Redis yet?
The solution is nice and simple, you just need to edit your app config, open app/config/app.php and replace this line:
'Redis' => 'Illuminate\Support\Facades\Redis',
with
'LaravelRedis' => 'Illuminate\Support\Facades\Redis',
Then you can get your Redis instance like this:
$redis = LaravelRedis::connection();
Quick and straightforward to solve, after an absolute nightmare to diagnose.
Important lesson learned today: it's probably not a good idea to use someone else's product name as your class name, especially if that class isn't distinguished by a package.
Caveat - third party Composer packages
There is probably a good reason that Laravel is still using 'Redis' as the default Redis alias - Composer packages. If you use a third party package that makes use of Redis with the default, you're screwed. In which case, you may want to remove the PHP Redis package entirely.
For example, on Ubuntu:
apt-get remove php5-redis
Don't forget to restart your PHP service as required.