Getting Started With Redis On Lumen
You developing a RESTful API on Lumen (http://lumen.laravel.com) or simply require a in-memory
data storage/database for quick caching purposes. Let's talk about Redis (https://redis.io).
As per the website:
‘Redis is an open source (BSD licensed), in-memory data structure store, used as a
database, cache and message broker. It supports data structures such as strings, hashes,
list, sets, sorted sets with range queries, bitmaps, hyperloglogs and geospatial indexes with
radius queries."
‘As per me; Ive been using it for my own RESTIul service and all | can tell you is that it's fast and very
simple to use ~ saving me /ots of time in development. Furthermore, its easy on the resources.
Lot us jump right into it
Note: If you haven't started working with Composer yet ~ this requires that. So go ahead Get started
with Composer (https:/ /thewebtier.com/php/what-is-composer/) first.
First off, Redis is a service that needs to be running to power your application. Head over
to https://redis.io/ (https:/ /redisio/) download and install it
If you're on Windows 10, fd suggest using the Ubuntu Bash terminal that now comes along with it.
Read: Installing Ubuntu Bash terminal on Windows 10
(http:/ /www.omgubuntu.co.uk/2016 /08/enable-bash-windows~10-anniversary-update)
‘Once Reais is up and running, head over to your Lumen project and require Redis, Lumen supports
Redis so that makes it much easier for us.
Make sure youve uncommented $app->withFacades() in bootstrap/app. php .
F composer require predis/predis (+1.2)
F conposer require sMluninate/redis (5.2.*)
“f Rogistoritin booeserap/app-php by calling $app->register(I12uninate\Redis\RedisserviceProvider::elass); in the
file, uncer Register Service Providers.
As por the Lumen docs; if you have not called $app->withetocuert() in your boststeap/app.phe file, then you
should call $app->contigure( database"); in the bootstrap/app.php file to ensure the Redis database configuration
's properly loaded.
“f Make sure your .enw Lumen contig le has this set cAcie_peavercredts. (Ifyou have .env.example instead
rename it to . env )
And that's it! Hit the RedisPHP (https://github.com/phpredis/phpredis) docs for all the commands.To use it in Lumen, you can call it these ways
F app(‘reais') (recommended)
F soppl ‘reais
F Sthis->app( reds’)
The reason | recommend app(‘redis*) is because it can be called anywhere, including closures and
80 on.
Basic Usage
Checking if a Key exists: app(‘redis')->exists(skey)
Setting a key/value:
app(*redis")->set($key, $value)
Getting a value by key: app(‘redis')->get ($key)
Setting an expiry for the key: 2p9(‘redis")->expire($key, $seconds)
And youte good to go!
If youre wondering what REST API was taking about, its Jikan (htpsi/ jkan.me/); an unoffictal API
platform that handles over 5,000 requests daily!