Hello devs in this example i will discuss about predis example and also show you how to install and use predis. You will learn also hot to list all key value pairs in redis using the predis library. Assumes that your redis is running locally on default port 6379 with no password auth.
This package predis relies on the autoloading features of PHP to load its files when needed and complies with the PSR-4 standard. This autoloading is handled automatically when dependencies are managed through Composer, but it is also possible to leverage its own autoloader in projects or scripts lacking any autoload facility:
This predis php library can be found on Packagist for an easier management of projects dependencies using Composer. This compressed archives of each release are available on GitHub.
So let's start:
Include Predis library.
require "Predis/Autoloader.php";
When creating a client instance without passing any connection parameter, Predis assumes 127.0.0.1
and 6379
as default host and port. The default timeout for the connect()
operation is 5 seconds:
Predis\Autoloader::register();
try {
$redis = new Predis\Client();
$redis = new Predis\Client(array(
"scheme" => "tcp",
"host" => "127.0.0.1"))
;
}
catch (Exception $e) {
echo "Couldn't connect to Redis";
echo $e->getMessage();
}
Get list of all keys. This creates an array of keys from the redis-cli output of "KEYS *"
$list = $redis->keys("*");
Optional: Sort Keys alphabetically
sort($list);
Loop through list of keys
foreach ($list as $key)
{
//Get Value of Key from Redis
$value = $redis->get($key);
//Print Key/value Pairs
echo "Key: $key and Value: $value ";
}
Disconnect from Redis
$redis->disconnect();
Recommended: Multiple Ways to Delete Laravel Redis Keys
Hope it can help you.
#php #packages #predis